Compare commits
3
Commits
master
..
711754bbcd
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
711754bbcd | ||
|
|
8d44c74535 | ||
|
|
20f2f00a60 |
+49
-9
@@ -1,11 +1,51 @@
|
||||
# Copy to .env for your LOCAL synthetic test environment; never commit .env.
|
||||
# These are logical interface suggestions; map actual framework names in REPORT.md.
|
||||
# Copy to .env and replace both password placeholders for a local synthetic stand.
|
||||
# Never commit .env. Existing .env files must be updated manually; see infra/README.md.
|
||||
HOST_PORT=8080
|
||||
|
||||
APP_ENABLED=true
|
||||
APP_HOST=0.0.0.0
|
||||
APP_PORT=8080
|
||||
APP_ENV=lab
|
||||
SESSION_TTL_SECONDS=3600
|
||||
# Choose credentials locally. File paths contain no secret values.
|
||||
DATABASE_URL_FILE=/run/secrets/database_url
|
||||
# Optional on 3, required use on 4 in lab2; Redis OR Valkey:
|
||||
SESSION_STORE=postgres
|
||||
CACHE_URL_FILE=/run/secrets/cache_url
|
||||
APP_READ_TIMEOUT=5s
|
||||
APP_WRITE_TIMEOUT=10s
|
||||
APP_IDLE_TIMEOUT=60s
|
||||
APP_SHUTDOWN_TIMEOUT=8s
|
||||
|
||||
APPLICATION_LOG_LEVEL=info
|
||||
APPLICATION_ENVIRONMENT=dev
|
||||
APPLICATION_SHUTDOWN_TIMEOUT=8s
|
||||
APPLICATION_REQUEST_RATE_LIMIT=100
|
||||
APPLICATION_BURST_RATE_LIMIT=100
|
||||
APPLICATION_RATE_LIMIT_TTL=1m
|
||||
|
||||
# Compose fixes container addresses and ports to the service names below.
|
||||
# These ports are not published on the host.
|
||||
POSTGRES_HOST=postgres
|
||||
POSTGRES_PORT=5432
|
||||
POSTGRES_USER=messenger
|
||||
POSTGRES_PASSWORD=replace-with-local-postgres-password
|
||||
POSTGRES_DATABASE=messenger
|
||||
POSTGRES_VERSION_TABLE=versions
|
||||
# The Go runner is not implemented; postgres bootstraps a new volume instead.
|
||||
POSTGRES_RUN_MIGRATIONS=false
|
||||
POSTGRES_MAX_CONNECTIONS=10
|
||||
|
||||
REDIS_HOST=redis
|
||||
REDIS_PORT=6379
|
||||
REDIS_USERNAME=default
|
||||
REDIS_PASSWORD=replace-with-local-redis-password
|
||||
REDIS_DB=0
|
||||
|
||||
JWT_ACCESS_TOKEN_LIFETIME=15m
|
||||
JWT_REFRESH_TOKEN_LIFETIME=24h
|
||||
# Container paths. Compose mounts ./certs read-only at /run/certs.
|
||||
JWT_PUBLIC_KEY_PATH=/run/certs/public_key.pem
|
||||
JWT_PRIVATE_KEY_PATH=/run/certs/private_key.pem
|
||||
|
||||
# Local HTTP defaults. Use secure cookies when serving through HTTPS.
|
||||
COOKIES_ENABLED=false
|
||||
COOKIES_DOMAIN=localhost
|
||||
COOKIES_PATH=/
|
||||
COOKIES_SECURE=false
|
||||
COOKIES_SAME_SITE=lax
|
||||
# Viper accepts a whitespace-separated list of origins.
|
||||
COOKIES_ALLOWED_ORIGINS=http://localhost:8080
|
||||
|
||||
@@ -28,5 +28,12 @@ coverage/
|
||||
.DS_Store
|
||||
.idea/
|
||||
.vscode/
|
||||
certs/
|
||||
# Keep small, sanitized evidence summaries in evidence/ under version control.
|
||||
# Inspect git diff --cached: ignore rules are not a secret scanner.
|
||||
|
||||
# Sanitized Redis experiment log accompanying evidence/redis-cache.md.
|
||||
!evidence/redis-cache-api.log
|
||||
|
||||
# Sanitized cache stampede experiment evidence.
|
||||
!evidence/cache-stampede/api.log
|
||||
|
||||
+32
@@ -0,0 +1,32 @@
|
||||
# syntax=docker/dockerfile:1
|
||||
|
||||
FROM --platform=$BUILDPLATFORM golang:1.27.2-alpine3.23 AS build
|
||||
|
||||
WORKDIR /src
|
||||
|
||||
COPY service/go.mod service/go.sum ./
|
||||
RUN go mod download
|
||||
|
||||
COPY service/ ./
|
||||
|
||||
ARG TARGETOS
|
||||
ARG TARGETARCH
|
||||
RUN CGO_ENABLED=0 GOOS=$TARGETOS GOARCH=$TARGETARCH \
|
||||
go build -mod=readonly -trimpath -ldflags="-s -w" -o /out/messenger ./cmd/app
|
||||
|
||||
FROM alpine:3.23.6
|
||||
|
||||
COPY --from=build --chmod=0555 /out/messenger /usr/local/bin/messenger
|
||||
|
||||
ENV APP_HOST=0.0.0.0 \
|
||||
APP_PORT=8080 \
|
||||
APP_SHUTDOWN_TIMEOUT=8s
|
||||
|
||||
USER 65532:65532
|
||||
EXPOSE 8080
|
||||
STOPSIGNAL SIGTERM
|
||||
|
||||
HEALTHCHECK --interval=10s --timeout=3s --start-period=5s --retries=3 \
|
||||
CMD wget -q -O /dev/null "http://127.0.0.1:${APP_PORT}/health/ready" || exit 1
|
||||
|
||||
ENTRYPOINT ["/usr/local/bin/messenger"]
|
||||
@@ -3,8 +3,12 @@ BASE_URL ?= http://localhost:8080
|
||||
CA_FILE ?=
|
||||
ACTION_SCRIPT ?=
|
||||
TLS_ARGS = $(if $(CA_FILE),--ca-file "$(CA_FILE)",)
|
||||
OPENAPI_SPEC := contracts/openapi.json
|
||||
GEN_OUTPUT := service/internal/gen/contracts/types.gen.go
|
||||
GEN_PACKAGE := contracts
|
||||
OAPI_CODEGEN ?= $(shell go env GOPATH)/bin/oapi-codegen
|
||||
|
||||
.PHONY: help check validate test load test-persistence
|
||||
.PHONY: help check validate test load test-persistence openapi-generate certs key-gen
|
||||
|
||||
help:
|
||||
@echo "check: offline structure; validate: full OpenAPI (requirements-dev.txt); test: running API; load: synthetic writes"
|
||||
@@ -24,3 +28,26 @@ load:
|
||||
test-persistence:
|
||||
@test -n "$(ACTION_SCRIPT)" || (echo "Set ACTION_SCRIPT to your implemented executable restart hook"; exit 2)
|
||||
$(PYTHON) tests/resilience.py --mode persistence --action-script "$(ACTION_SCRIPT)" --base-url "$(BASE_URL)" $(TLS_ARGS)
|
||||
|
||||
openapi-generate:
|
||||
@mkdir -p $(dir $(GEN_OUTPUT))
|
||||
@echo "Generating Go types from $(OPENAPI_SPEC)..."
|
||||
@set -o pipefail; \
|
||||
jq '(.components.schemas.ChatPage.properties.next_cursor.type, .components.schemas.MessagePage.properties.next_cursor.type) |= "string" | (.components.schemas.ChatPage.properties.next_cursor.nullable, .components.schemas.MessagePage.properties.next_cursor.nullable) = true' $(OPENAPI_SPEC) | \
|
||||
$(OAPI_CODEGEN) -generate types -package $(GEN_PACKAGE) -o $(GEN_OUTPUT) /dev/stdin
|
||||
|
||||
key-gen: create-dir gen-private-key gen-public-key
|
||||
|
||||
create-dir:
|
||||
@mkdir -p certs
|
||||
gen-private-key:
|
||||
@openssl genrsa -out certs/private_key.pem 2048
|
||||
gen-public-key:
|
||||
@openssl rsa -in certs/private_key.pem -pubout -outform PEM -out certs/public_key.pem
|
||||
|
||||
certs: gen-key gen-crt
|
||||
|
||||
gen-key:
|
||||
@openssl genrsa -out ./certs/server.key 2048
|
||||
gen-crt:
|
||||
@openssl req -new -x509 -key ./certs/server.key -out ./certs/server.crt -days 365
|
||||
|
||||
@@ -1,37 +1,344 @@
|
||||
# Отчёт — лабораторная 2
|
||||
# Отчёт — лабораторная 2: PostgreSQL, сессии и Redis
|
||||
|
||||
- Автор, группа: TODO
|
||||
- Целевая оценка; выбранный трек 5, если нужен: TODO
|
||||
- Commit/PR: TODO после публикации
|
||||
- Использованные источники, библиотеки и помощь ИИ: TODO
|
||||
- Автор: Поликарпов Даниил Александрович. Группа: БПИ2303.
|
||||
- Дата оформления: 6 ноября 2026 года.
|
||||
- Выбранный эксперимент уровня «5»: трек 1, cache stampede — одновременные промахи кэша.
|
||||
- Базовый commit: `9493763dc8ee29907a77026329e474974209b646`. Реализация и эксперименты относятся к изменённому рабочему дереву поверх этого commit; сам commit не содержит всех описанных изменений. Ссылка на PR не предоставлена.
|
||||
- ChatGPT/Codex использовался для проверки функционала и подготовки отчёта. Версии библиотек закреплены в [go.mod](service/go.mod); источники и исходные результаты приведены ниже.
|
||||
|
||||
## Запуск из чистого clone
|
||||
Цель работы — перенести пользователей, чаты, участников, сообщения и сессии в PostgreSQL, заменить идентификацию через `X-User-Id` аутентификацией и использовать Redis как необязательный кэш. Завершён эксперимент с защитой от повторных SQL-чтений при наплыве запросов. Полное выполнение всех требований уровней 3 и 4 имеющимися доказательствами не подтверждено; выполненный трек сам по себе не означает получение оценки «5».
|
||||
|
||||
TODO: версии runtime/образов, prerequisites, команды создания локальных secrets/.env, build, миграций, запуска, ожидания готовности, тестов и остановки. Указать необходимые действия оператора. Не вставлять секреты. Отдельно указать безопасную остановку и команду намеренного удаления учебных данных.
|
||||
## 1. Запуск из чистого clone
|
||||
|
||||
## Архитектура и решения
|
||||
### 1.1. Предварительные условия и версии
|
||||
|
||||
TODO: схема процессов/хранилищ, источник истины, транзакционные границы, ограничения. Что перенесено из lab1, что изменено в этой работе. Соответствие переменных из .env.example реальной конфигурации.
|
||||
Нужны Git, Docker Engine с Docker Compose v2, поддерживающим `--wait`, OpenSSL, Make и Python 3.9+. На Linux для приведённой настройки доступа к ключам нужна утилита `setfacl` и поддержка POSIX ACL файловой системой. Go на хосте нужен для локальной сборки; Docker собирает приложение самостоятельно.
|
||||
|
||||
## Доказательства критериев
|
||||
| Компонент | Версия / образ |
|
||||
| --- | --- |
|
||||
| Язык Go | `go 1.27.0` в go.mod; сборка контейнера `golang:1.27.2-alpine3.23` |
|
||||
| Runtime API | `alpine:3.23.6`, пользователь `65532:65532` |
|
||||
| PostgreSQL | `postgres:17.11-alpine3.23` |
|
||||
| Redis | `redis:8.2.11-alpine3.22` |
|
||||
| HTTP-маршрутизация | chi v5.5.0 |
|
||||
| Доступ к PostgreSQL / миграции | pgx v5.11.0 / Tern v2.4.3 |
|
||||
| Redis / объединение загрузок | go-redis v9.23.0 / x/sync v0.23.0 |
|
||||
|
||||
| Критерий README | Команда/сценарий | Наблюдаемый результат | Файл доказательства |
|
||||
Команды этого раздела — инструкция воспроизведения. При оформлении отчёта они заново не выполнялись. Проверявшиеся ранее сборки и сценарии перечислены в разделе 4. Инструкция рассчитана на итоговое дерево исходников с описанными изменениями, а не только на базовый commit.
|
||||
|
||||
```sh
|
||||
git clone https://gitea.privcloud.tech/mtusi2026/mtusi2026lab2.git
|
||||
cd mtusi2026lab2
|
||||
```
|
||||
|
||||
### 1.2. Локальное окружение
|
||||
|
||||
Следующая команда создаёт новый `.env` из [примера](.env.example), генерирует отдельные пароли PostgreSQL и Redis и включает миграции. Существующий `.env` не перезаписывается; пароли не выводятся. Выполнять из корня проекта:
|
||||
|
||||
```sh
|
||||
umask 077
|
||||
python3 - <<'PY'
|
||||
from pathlib import Path
|
||||
import re
|
||||
import secrets
|
||||
|
||||
text = Path('.env.example').read_text()
|
||||
values = {
|
||||
'POSTGRES_PASSWORD': secrets.token_urlsafe(32),
|
||||
'REDIS_PASSWORD': secrets.token_urlsafe(32),
|
||||
'POSTGRES_RUN_MIGRATIONS': 'true',
|
||||
}
|
||||
for key, value in values.items():
|
||||
text = re.sub(r'^' + key + r'=.*$', key + '=' + value, text, flags=re.MULTILINE)
|
||||
with Path('.env').open('x') as stream:
|
||||
stream.write(text)
|
||||
PY
|
||||
```
|
||||
|
||||
В `.env.example` сохранились устаревшие комментарий об отсутствии Go-мигратора и значение `POSTGRES_RUN_MIGRATIONS=false`. В текущем коде мигратор реализован; без его включения пустая БД не получит схему. Для уже существующего `.env` оператор должен самостоятельно проверить пароли, адреса и установить `POSTGRES_RUN_MIGRATIONS=true`. Ссылка на `infra/README.md` в комментарии примера неактуальна: этого файла в текущем дереве нет.
|
||||
|
||||
Для описанного Compose адреса внутри сети — `postgres:5432` и `redis:6379`; API слушает `0.0.0.0:8080`, на хост опубликован только `127.0.0.1:8080`. `HOST_PORT` меняет хостовый порт. `APP_PORT` следует оставить равным 8080: целевой порт публикации в Compose закреплён на 8080. PostgreSQL и Redis на хост не публикуются.
|
||||
|
||||
Пароли и ключи необходимо сохранять между перезапусками. Изменение пароля PostgreSQL в `.env` само по себе не меняет пароль роли в существующем volume.
|
||||
|
||||
### 1.3. RSA-ключи
|
||||
|
||||
На чистом clone создать пару ключей для подписи JWT. При повторном запуске существующие ключи нужно использовать повторно: их замена делает прежние подписанные сессии непригодными.
|
||||
|
||||
```sh
|
||||
umask 077
|
||||
make key-gen
|
||||
chmod 600 certs/private_key.pem
|
||||
chmod 644 certs/public_key.pem
|
||||
```
|
||||
|
||||
Команда `make key-gen` генерирует RSA-ключ 2048 бит и публичную часть. Это ключи JWT, а не TLS-сертификат; локальный API работает по HTTP. Каталог `certs` монтируется только для чтения в `/run/certs`.
|
||||
|
||||
API работает от UID 65532. На Linux выдать этому UID доступ, сохраняя приватный ключ закрытым для остальных пользователей:
|
||||
|
||||
```sh
|
||||
setfacl -m u:65532:rx certs
|
||||
setfacl -m u:65532:r certs/private_key.pem certs/public_key.pem
|
||||
```
|
||||
|
||||
На Docker Desktop отображение прав зависит от механизма файлового обмена. После сборки проверить чтение обоих файлов из контейнера командой ниже; ошибка требует настройки прав bind mount для UID 65532. Открывать приватный ключ всем пользователям через `chmod 644` не требуется.
|
||||
|
||||
### 1.4. Сборка, миграции и готовность
|
||||
|
||||
```sh
|
||||
docker compose --env-file .env config --quiet
|
||||
docker compose --env-file .env build api
|
||||
docker compose --env-file .env run --rm --no-deps --entrypoint sh api \
|
||||
-c 'test -r /run/certs/private_key.pem && test -r /run/certs/public_key.pem'
|
||||
docker compose --env-file .env up -d --no-build --wait --wait-timeout 120
|
||||
curl --fail --silent --show-error http://127.0.0.1:8080/health/live
|
||||
curl --fail --silent --show-error http://127.0.0.1:8080/health/ready
|
||||
docker compose --env-file .env ps -a
|
||||
```
|
||||
|
||||
На старте API Tern применяет встроенные SQL-миграции и ведёт версию в таблице `versions`. Отдельный SQL-bootstrap контейнера PostgreSQL в текущем Compose не настроен. Ошибка миграции останавливает запуск API. При повторном запуске мигратор использует сохранённую версию; отдельный эксперимент чистого первого запуска и проверки отсутствия дублей в этом отчёте не заявлен.
|
||||
|
||||
Compose ожидает здоровый PostgreSQL перед запуском API. Redis является необязательной зависимостью по доступности: API не зависит от его healthcheck и продолжает запуск при ошибке стартового PING. При этом конфигурационные реквизиты Redis, включая пароль для Compose, всё равно должны быть заданы.
|
||||
|
||||
`/health/live` отражает жизнь HTTP-процесса. Реальный `/health/ready` проверяет флаг запущенного HTTP-сервера, а не соединение с PostgreSQL. Поэтому его 200 и статус Docker `healthy` не доказывают работоспособность обязательного пути БД при последующем отказе PostgreSQL.
|
||||
|
||||
Для диагностики использовать выборочные журналы; полный вывод конфигурации с секретами в отчёт не сохранять:
|
||||
|
||||
```sh
|
||||
docker compose --env-file .env logs --tail 100 api
|
||||
```
|
||||
|
||||
При нестандартном `HOST_PORT` заменить порт в curl и передать соответствующий `BASE_URL` проверкам.
|
||||
|
||||
### 1.5. Готовые проверки и остановка
|
||||
|
||||
Доступные команды проекта:
|
||||
|
||||
```sh
|
||||
make check
|
||||
make test BASE_URL=http://127.0.0.1:8080
|
||||
make test-persistence ACTION_SCRIPT=scripts/restart.sh BASE_URL=http://127.0.0.1:8080
|
||||
```
|
||||
|
||||
В [tests/README.md](tests/README.md) описана методика. `make test` создаёт синтетические данные. Persistence использует [scripts/restart.sh](scripts/restart.sh): он пересобирает API, останавливает его, пересоздаёт PostgreSQL и Redis с прежними volumes, затем пересоздаёт API и ждёт healthchecks. Для выполнения hook нужен executable bit. Сохранённых результатов этих двух проверок в приложенных материалах нет; команды здесь не обозначают PASS. При подготовке данного отчёта новые тесты не писались и эти проверки не запускались.
|
||||
|
||||
Обычная остановка сохраняет именованные volumes и локальные ключи:
|
||||
|
||||
```sh
|
||||
docker compose --env-file .env down
|
||||
```
|
||||
|
||||
Следующая отдельная команда предназначена только для намеренного сброса учебного стенда. Она удаляет volumes PostgreSQL и Redis текущего Compose-проекта, включая пользователей, сообщения, сессии и кэш; это не способ обычного перезапуска:
|
||||
|
||||
```sh
|
||||
docker compose --env-file .env down --volumes
|
||||
```
|
||||
|
||||
### 1.6. Фактически используемая конфигурация
|
||||
|
||||
| Переменные | Назначение и текущее поведение |
|
||||
| --- | --- |
|
||||
| `HOST_PORT`, `APP_HOST`, `APP_PORT` | Публикация хостового порта и адрес HTTP-listener; целевой порт публикации — 8080 |
|
||||
| `APP_ENABLED` | В Compose принудительно задано `true` |
|
||||
| `APP_READ_TIMEOUT`, `APP_WRITE_TIMEOUT`, `APP_IDLE_TIMEOUT`, `APP_SHUTDOWN_TIMEOUT` | Таймауты HTTP и graceful shutdown; значения Compose по умолчанию 5/10/60/8 секунд |
|
||||
| `POSTGRES_HOST`, `POSTGRES_PORT`, `POSTGRES_USER`, `POSTGRES_PASSWORD`, `POSTGRES_DATABASE` | Соединение с PostgreSQL; внутри Compose следует использовать имя сервиса |
|
||||
| `POSTGRES_RUN_MIGRATIONS`, `POSTGRES_VERSION_TABLE` | Включение Tern и таблица версии; для первого запуска нужны `true` и `versions` |
|
||||
| `POSTGRES_MAX_CONNECTIONS` | Читается в конфигурацию, но не применяется к пулу: `config.Postgres` не реализует ожидаемый `GetMaxConnections() int32`; фактически остаётся настройка pgxpool по умолчанию |
|
||||
| `REDIS_HOST`, `REDIS_PORT`, `REDIS_USERNAME`, `REDIS_PASSWORD`, `REDIS_DB` | Подключение к Redis; время операций ограничено константами в коде, отдельных env-переменных таймаутов нет |
|
||||
| `JWT_REFRESH_TOKEN_LIFETIME` | Срок Bearer-сессии, по умолчанию в Compose 24 часа |
|
||||
| `JWT_ACCESS_TOKEN_LIFETIME` | Срок отдельного access JWT, по умолчанию 15 минут; обязательный API принимает session token, а не этот access token |
|
||||
| `JWT_PUBLIC_KEY_PATH`, `JWT_PRIVATE_KEY_PATH` | Контейнерные пути `/run/certs/public_key.pem` и `/run/certs/private_key.pem` |
|
||||
| `SESSION_TTL_SECONDS` | Требуется контрактом лабораторной, но текущим загрузчиком конфигурации не поддерживается; для короткого срока в реализации используется `JWT_REFRESH_TOKEN_LIFETIME`, например `2s` |
|
||||
| `APPLICATION_ENVIRONMENT`, `APPLICATION_LOG_LEVEL`, `APPLICATION_SHUTDOWN_TIMEOUT` | Читаются конфигурацией приложения; наличие этих полей не заменяет фактическую настройку HTTP shutdown через `APP_SHUTDOWN_TIMEOUT` или обработчика slog |
|
||||
| `APPLICATION_REQUEST_RATE_LIMIT`, `APPLICATION_BURST_RATE_LIMIT`, `APPLICATION_RATE_LIMIT_TTL` | Читаются в конфигурацию; в текущем запуске rate-limit middleware не подключён |
|
||||
| `COOKIES_*` | Остались в примере окружения; текущий основной Config их не загружает, обязательный путь аутентификации использует заголовок Bearer |
|
||||
|
||||
## 2. Архитектура и решения
|
||||
|
||||
### 2.1. Компоненты и источник истины
|
||||
|
||||
Клиент обращается к HTTP API на Go. Маршрутизатор chi применяет request ID, логирование и проверку сессии; обработчики декодируют и проверяют JSON, сервисы выполняют бизнес-операции, репозитории используют pgx и go-redis. Контракт находится в [OpenAPI](contracts/openapi.json) и [описании семантики](contracts/README.md).
|
||||
|
||||
PostgreSQL — источник истины для пользователей, чатов, членства, сообщений и сессий. Redis хранит только копии метаданных чатов. Отказ или очистка кэша не должны удалять сообщения и отзывать сессии. Это подтверждено для stop/start Redis; полный рестарт всех сервисов остаётся отдельной неподтверждённой проверкой.
|
||||
|
||||
По сравнению с lab1 идентификация через `X-User-Id` заменена входом по паролю и серверной сессией. Состояние перенесено в PostgreSQL; добавлены постоянные volumes и кэш. Полная совместимость обязательного API должна подтверждаться публичным smoke, результата которого в материалах нет.
|
||||
|
||||
### 2.2. Схема и транзакционные границы
|
||||
|
||||
[SQL-миграции](service/migrations) встроены в бинарник через `go:embed` и применяются Tern последовательно.
|
||||
|
||||
| Таблица | Основные данные и ограничения |
|
||||
| --- | --- |
|
||||
| `users` | UUID PK, уникальный username, имя, Argon2id-хэш пароля, времена; CHECK формата username и непустых данных |
|
||||
| `refresh_tokens` | UUID PK сессии, FK пользователя, хэш токена, роль, `expires_at`, `revoked_at`; индексы по пользователю и сроку |
|
||||
| `chats` | UUID PK, непустой заголовок, время; индекс `(created_at, id)` |
|
||||
| `chat_members` | Составной PK `(chat_id, user_id)`, FK на чат и пользователя; дополнительный индекс `(user_id, chat_id)` |
|
||||
| `messages` | UUID PK, чат, отправитель, текст и время; составной FK `(chat_id, sender_id)` на членство и индекс `(chat_id, created_at, id)` |
|
||||
|
||||
Создание чата и всех участников выполняется одной транзакцией: сначала INSERT чата, затем INSERT участников. Сервис проверяет отсутствие дублей и включение создателя; FK не позволяет записать неизвестного пользователя. Commit выполняется только после успешного завершения всей операции; при ошибке или panic менеджер пытается выполнить rollback. Это описание кода, а не результат отдельного fault-injection эксперимента rollback.
|
||||
|
||||
Создание сообщения — один параметризованный INSERT после проверки доступа. Успешный ответ отправляется после успешного выполнения SQL. Создание и отзыв серверной сессии используют транзакции; при logout строка сессии блокируется для проверки и обновления `revoked_at`. Прикладной COMMIT не является самостоятельным доказательством сохранности при потере диска или питания: отдельной проверки durability и восстановления backup нет.
|
||||
|
||||
### 2.3. Аутентификация и доступ
|
||||
|
||||
`POST /api/v1/users` регистрирует пользователя. Пароль хранится в виде Argon2id: память 64 MiB, 3 прохода, параллелизм 4, случайная соль 16 байт и ключ 32 байта. Пароль и хэш не включаются в публичный объект User.
|
||||
|
||||
`POST /api/v1/auth/sessions` принимает Basic и возвращает `201` с `token`, `token_type`, `expires_at`, `user`. Формат токена реализации — JWT RS256; клиент передаёт его как непрозрачную строку и не должен разбирать claims. Возвращается refresh/session JWT. Сгенерированный отдельно access JWT не подходит для обязательного session middleware.
|
||||
|
||||
Для каждого защищённого запроса middleware проверяет подпись и claims, читает `refresh_tokens`, проверяет срок, отсутствие отзыва, соответствие пользователя и роли, затем сравнивает хэш токена. Сессионный хэш вычисляется как bcrypt от hex-представления SHA-256 токена, с `bcrypt.DefaultCost`. Это отдельная CPU-работа даже при попадании чата в Redis. `DELETE /api/v1/auth/sessions/current` отзывает текущую сессию. `X-User-Id` не используется этим middleware как источник идентификации.
|
||||
|
||||
Членство проверяется в SQL или по `MemberIDs` кэшированного чата. Постороннему возвращается 404, чтобы не раскрывать наличие чужого ресурса. Положительный вход и отказ постороннему проверены экспериментом; logout, неверный пароль, отсутствие Bearer и expiry не объявляются отдельно проверенными без соответствующих результатов.
|
||||
|
||||
### 2.4. История и read-after-write
|
||||
|
||||
История читается из PostgreSQL по `chat_id`, отсортирована по `(created_at, id)` и использует keyset-условие `(created_at, id) > (cursor_created_at, cursor_id)`. Курсор API содержит UUID записи; сервер получает её позицию в пределах нужного ресурса. Размер страницы ограничен 1–100, по умолчанию 50; дополнительная запись определяет наличие следующей страницы. OFFSET и кэш истории не используются.
|
||||
|
||||
Индекс `idx_messages_chat_id_created_at_id` соответствует фильтрации чата и порядку выдачи. Это обоснование по структуре запроса; отсутствие полного scan на большой истории ещё не доказано EXPLAIN (ANALYZE, BUFFERS) на ≥10 000 сообщениях.
|
||||
|
||||
После подтверждённого POST следующий запрос истории другого участника увидел ID сообщения. Проверка выполнялась с одной API-репликой. Отдельного snapshot между страницами нет; при конкурентных вставках новые записи с позицией до уже выданного курсора могут не попасть в дальнейший обход. Многорепличная конфигурация и распределённая синхронизация часов не исследовались.
|
||||
|
||||
### 2.5. Политика кэша и singleflight
|
||||
|
||||
Ключ Redis — `chat:<UUID>`, значение — JSON с ID, заголовком, списком участников и временем создания. Чат сохраняется в кэш после успешного чтения из PostgreSQL. Срок хранения не задан (`SET` с expiration=0); автоматической инвалидации нет. В обязательном API нет изменения или удаления состава участников, поэтому существующий сценарий не содержит такого источника устаревших разрешений. При добавлении этих операций потребуется инвалидация или иная политика согласованности.
|
||||
|
||||
При промахе или ошибке Redis приложение читает PostgreSQL. `redis.Nil` обозначает отсутствие ключа, остальные ошибки чтения логируются отдельно. Ошибка записи в кэш не отменяет успешное чтение из БД. Redis использует AOF с `appendfsync everysec` и именованный volume; наблюдалось сохранение ключа при корректном stop/start, а не при аварийном отключении питания.
|
||||
|
||||
В `GetForMember` singleflight объединяет одновременные загрузки по `(ChatID, UserID)` внутри одного процесса. Общая загрузка повторно проверяет Redis, читает БД при необходимости и заполняет кэш. Пользователь входит в ключ, поскольку SQL-результат зависит от его членства: нельзя разделить отказ одного пользователя с другим. Отмена ожидающего HTTP-клиента не отменяет общую загрузку; для неё установлен отдельный таймаут 2 секунды. Членство проверяется перед возвратом результата.
|
||||
|
||||
Dial/read/write/pool timeout Redis установлены по 200 мс, повторы команд отключены (`MaxRetries=-1`), `DialerRetries=1`; GET, SET и стартовый PING имеют отдельные контексты по 300 мс. Чтение и последующая запись могут расходовать разные бюджеты; 300 мс не является общим таймаутом HTTP-запроса. Обычные SQL-пути вне общей загрузки не получают от HTTP WriteTimeout отдельного гарантированного срока выполнения запроса к БД.
|
||||
|
||||
Диагностика: `chat_cache_hit`, `chat_cache_miss`, `chat_cache_read_error`, `chat_db_lookup`; ошибки заполнения кэша записываются как `failed to cache chat`. Отсутствие `chat_db_lookup` означает экономию чтения чата, но не отсутствие SQL проверки сессии.
|
||||
|
||||
## 3. Соответствие критериям лабораторной
|
||||
|
||||
«Подтверждено» означает наличие результата выполнения в приложенных материалах. «По коду» означает найденную реализацию без отдельного результата требуемой проверки. «Не проверено» не является PASS; наличие команды или скрипта не заменяет его выполнение.
|
||||
|
||||
| Критерий README | Реализация / команда воспроизведения | Фактический статус | Основание / доказательство |
|
||||
| --- | --- | --- | --- |
|
||||
| Публичный smoke | make test | TODO | TODO |
|
||||
| Остальные пункты уровня 3 | TODO | TODO | TODO |
|
||||
| Все пункты уровня 4, если заявлен | TODO | TODO | TODO |
|
||||
| Выбранный трек 5, если заявлен | TODO | TODO | TODO |
|
||||
| Уровень 3: минимум lab1 и переход на новую аутентификацию | `make test` | По коду переход реализован; полный публичный smoke не подтверждён | [Auth middleware](service/internal/pkg/rest/middleware/auth.go), [публичный сценарий](tests/smoke.py) |
|
||||
| Сохранность обязательных данных и действующих сессий после рестарта API и всех хранилищ | `make test-persistence ACTION_SCRIPT=scripts/restart.sh` | Не проверено полным сценарием; отдельно подтверждены Redis restart и использование прежней сессии | [Hook](scripts/restart.sh), [результаты Redis](evidence/cache-stampede/README.md) |
|
||||
| Пользователи, чаты, участники и сообщения в PostgreSQL; PK/FK/unique | SQL-схема и операции репозиториев | По коду ограничения есть; синтетические операции создания и чтения выполнены | [Миграции](service/migrations), [проверки эксперимента](evidence/cache-stampede/summary.json) |
|
||||
| Версионируемые миграции с нуля и повтор без дублей | Tern при `POSTGRES_RUN_MIGRATIONS=true`, повторный запуск API | По коду реализовано; отдельного протокола чистой БД и сверки дублей нет | [Мигратор](service/internal/pkg/migrator/tern.go) |
|
||||
| Атомарное создание чата | Транзакция создания чата и участников; отказ при ошибке второго INSERT | По коду реализовано; принудительный rollback не проверен | [Репозиторий чатов](service/internal/adapter/repository/storage/chats.go), [транзакции](service/internal/pkg/postgres/txmanager/tx.go) |
|
||||
| Basic только для входа, Bearer на бизнес-запросах | Создание сессии и GET чата в эксперименте | Положительные запросы подтверждены; отдельный отрицательный сценарий Basic на бизнес-endpoint не сохранён | [Auth handler](service/internal/adapter/controller/http/authHandler.go), [скрипт эксперимента](scripts/cache_stampede.py) |
|
||||
| `X-User-Id` не даёт доступ | Проверка `Authorization: Bearer` в middleware | По коду; отдельного HTTP-результата для одного `X-User-Id` нет | [Middleware](service/internal/pkg/rest/middleware/auth.go) |
|
||||
| Expiry, logout и password KDF | Проверка серверной сессии; DELETE current; Argon2id | KDF и проверки реализованы по коду; expiry/logout отдельно не подтверждены | [Auth service](service/internal/service/auth/svc.go), [Argon2id](service/internal/pkg/encrypting/argon2id.go) |
|
||||
| `make test` и `make test-persistence` проходят | Команды раздела 1.5 | Не проверено по имеющимся результатам | [Инструкции публичных проверок](tests/README.md) |
|
||||
| Secrets и volumes не попадают в Git | Правила исключений и подготовка локального окружения | Правила есть; история Git целиком на секреты не аудировалась | [.gitignore](.gitignore); результаты экспериментов обезличены |
|
||||
| Уровень 4: осмысленный Redis-кэш, источник истины, expiry и инвалидация | GET чата после удаления одного ключа и повторный GET | Подтверждены miss → PostgreSQL → hit; политика хранения описана в разделе 2.5 | [Первый сценарий](evidence/redis-cache.md), [логи](evidence/redis-cache-api.log) |
|
||||
| Параметризованный SQL, ограниченный пул и таймауты | Репозитории pgx, конфигурация соединений | SQL параметризован; Redis и HTTP имеют таймауты; `POSTGRES_MAX_CONNECTIONS` не применяется, общего SQL deadline нет | [Репозитории](service/internal/adapter/repository/storage), [пул](service/internal/pkg/postgres/postgres.go), [Redis config](service/internal/config/redis.go) |
|
||||
| Гонка регистрации одинакового username | Параллельные POST одного username | Не проверено; unique constraint и преобразование в 409 есть по коду | [Users repo](service/internal/adapter/repository/storage/users.go) |
|
||||
| Rollback составной операции | Ошибка после INSERT чата до завершения участников | Не проверено экспериментом | [Транзакции](service/internal/pkg/postgres/txmanager/tx.go) |
|
||||
| Индекс истории и EXPLAIN на ≥10 000 сообщений | EXPLAIN (ANALYZE, BUFFERS) для запроса истории | Индекс и keyset есть; требуемый EXPLAIN и объём не подтверждены | [Миграция сообщений](service/migrations/005_create_messages_table.sql), [запрос](service/internal/adapter/repository/storage/messages.go) |
|
||||
| Автоматические короткий TTL, logout, неверный пароль | Отдельные отрицательные сценарии сессий | Не проверено; `SESSION_TTL_SECONDS` не поддерживается текущей конфигурацией | [JWT config](service/internal/config/jwt.go), [контракт](contracts/README.md) |
|
||||
| Недоступность Redis и БД; отсутствие анонимного доступа при отказе | Redis stop/start; отдельный отказ PostgreSQL и анонимный запрос | Обход отказа Redis подтверждён; PostgreSQL failure и анонимный запрос в условиях отказа не проверены | [Отказ Redis](evidence/redis-cache.md), [повторный сценарий](evidence/cache-stampede/README.md) |
|
||||
| Уровень 5, трек 1: конкурентный stampede, защита, SQL и latency до/после | `python3 scripts/cache_stampede.py` после подготовки двух образов | Подтверждено: 10 × 32 GET, SELECT чата 308 → 10; ошибки ответов — 0 | [Методика](evidence/cache-stampede/README.md), [SQL-снимки](evidence/cache-stampede/summary.json), [CSV](evidence/cache-stampede/requests.csv) |
|
||||
| Read-after-write из контракта | POST сообщения → GET истории другим участником | Подтверждено на одной API-реплике: ID сообщения найден после записи и после Redis restart | [Checks](evidence/cache-stampede/summary.json) |
|
||||
| Восстановление после рестарта кэша | Redis stop/start, затем DEL ключа и повторный наплыв | Подтверждено: API не перезапускался, после DEL один SELECT чата на 32 GET | [Журнал и состояния](evidence/cache-stampede/api.log) |
|
||||
|
||||
TODO: добавить отдельную строку для каждого заявленного критерия. PASS без команды и наблюдения не является доказательством. Проверка инфраструктурного hook требует подтверждения, какие реальные процессы/хранилища перезапущены.
|
||||
Трек 2 с ≥100 000 сообщений, сравнением двух вариантов индекса/запроса и backup → restore не выбран и не заявляется выполненным.
|
||||
|
||||
## Эксперименты и отказы
|
||||
## 4. Эксперименты и отказы
|
||||
|
||||
TODO: гипотеза, hardware/лимиты, версии, объём данных, профиль нагрузки, concurrency/arrival rate, длительность/прогрев, повторы, успешные RPS, ошибки, p50/p95/p99, CPU/RAM. Сохранить raw summary без tokens и объяснить ограничения измерения.
|
||||
### 4.1. Последовательный кэш и необязательный Redis
|
||||
|
||||
| Воздействие | Что ожидаем | Что наблюдали | Время восстановления / потеря данных |
|
||||
[Первый эксперимент](evidence/redis-cache.md) выполнен 6 ноября 2026 года до добавления singleflight. Удалялся только ключ синтетического чата. Первый GET дал `chat_cache_miss` и `chat_db_lookup`, повторный — `chat_cache_hit` без чтения чата из БД. Посторонний пользователь при заполненном кэше получил 404.
|
||||
|
||||
При остановленном Redis GET вернул 200 за 56,076 мс. API был пересоздан при всё ещё остановленном Redis и продолжил работу: GET — 200 за 72,418 мс. После запуска Redis кэш восстановился без ещё одного перезапуска API. Эти результаты относятся к предшествующей сборке, идентифицированной в соответствующем отчёте; отказ Redis также повторён на версии с singleflight в следующем эксперименте.
|
||||
|
||||
### 4.2. Cache stampede: гипотеза и методика
|
||||
|
||||
Гипотеза: при одновременном промахе один и тот же пользователь многократно читает чат из PostgreSQL; singleflight позволит выполнять одну общую загрузку.
|
||||
|
||||
Итоговый сравнительный прогон: 6 ноября 2026 года, 09:49:37–09:50:20 UTC. Стенд — Docker Engine 29.7.2, Linux/aarch64, 14 CPU, 8 320 954 368 байт памяти Docker VM (примерно 7,75 GiB), без отдельных CPU/RAM-лимитов контейнеров. PostgreSQL 17.11, Redis 8.2.11, одна API-реплика. Один синтетический чат с двумя участниками; третий пользователь посторонний.
|
||||
|
||||
Перед исправлением собран baseline, затем отдельный образ с singleflight. Их точные IDs, хэши исходников и [patch изменения](evidence/cache-stampede/singleflight.patch.txt) сохранены вместе с результатами. Полная инструкция восстановления baseline в отдельной копии и сборки двух образов находится в [методике](evidence/cache-stampede/README.md); переключатель отключения защиты в приложение не добавлялся. В текущем дереве patch называется `singleflight.patch.txt`; при воспроизведении команды из методики нужно использовать это актуальное имя вместо прежнего `singleflight.patch`:
|
||||
|
||||
```sh
|
||||
# В отдельной временной копии итоговых исходников baseline восстанавливается так:
|
||||
git apply --reverse evidence/cache-stampede/singleflight.patch.txt
|
||||
```
|
||||
|
||||
Обратный patch следует применять только в копии для сборки baseline, сохраняя основное рабочее дерево с исправлением.
|
||||
|
||||
Для обеих версий проведены 10 холодных наплывов по 32 GET одного участника с общим стартовым барьером. Перед каждым удалялся только экспериментальный ключ. Чтобы промахи воспроизводились на быстрой локальной БД, отдельная транзакция получала `ACCESS EXCLUSIVE` на таблицу `chats` и освобождала её через 200 мс после барьера. Это искусственная задержка чтения, одинаковая до/после; она блокирует всю таблицу и предназначена только для локального стенда. Дополнительно выполнены по 5 тёплых наплывов по 32 GET без блокировки. Между группами была пауза 300 мс.
|
||||
|
||||
SQL измерялся по разности `pg_stat_statements.calls` до/после каждого прогона, отдельно для SELECT чата и SELECT сессии. Расширение и preload включались временно, без глобального сброса статистики; после завершения убраны с восстановлением обычного Compose и сохранением volumes. Это серверный подсчёт SQL, а не вывод только из `chat_db_lookup`.
|
||||
|
||||
HTTP-длительности измерены монотонными часами клиента; timeout — 5 секунд. Перцентили рассчитаны ближайшим рангом по всем запросам серии. Все успешные GET сравнены с полным объектом чата. В дополнительных сценариях получены ожидаемые 404, ошибки доступа не смешаны с сетевыми сбоями.
|
||||
|
||||
### 4.3. Результаты до и после
|
||||
|
||||
| Версия / режим | Группы / GET | SELECT чата | SELECT сессии | p50, мс | p95, мс | p99, мс | Ошибки ответов |
|
||||
| --- | --- | --- | --- | --- | --- | --- | --- |
|
||||
| До, пустой кэш | 10 / 320 | 308 | 320 | 208,124 | 215,502 | 260,385 | 0 |
|
||||
| После, пустой кэш | 10 / 320 | 10 | 320 | 207,056 | 209,568 | 210,032 | 0 |
|
||||
| До, заполненный кэш | 5 / 160 | 0 | 160 | 138,915 | 161,038 | 172,568 | 0 |
|
||||
| После, заполненный кэш | 5 / 160 | 0 | 160 | 136,467 | 172,304 | 200,266 | 0 |
|
||||
|
||||
Чтения чата сократились на **96,75%**: в среднем 30,8 → 1 на холодный наплыв. С учётом SELECT проверки сессий эти два вида SQL сократились с 628 до 330, на **47,45%**. Проверки сессий по-прежнему выполняются на каждом GET, поэтому «один SELECT чата» не означает «один SQL на весь наплыв».
|
||||
|
||||
В холодной серии p50 почти не изменился из-за общей задержки 200 мс; p99 уменьшился примерно на 50 мс. Тёплый p95, наоборот, вырос. Один последовательный порядок «до → после», небольшой объём и искусственная блокировка не доказывают устойчивое ускорение или предел throughput. Подтверждённый результат — устранение дублирующихся загрузок для выбранного ключа, а не ускорение любого HTTP-запроса.
|
||||
|
||||
Во время обеих фаз одинаково собирался `docker stats`. Максимальные значения среди восьми выборок каждой фазы:
|
||||
|
||||
| Контейнер | CPU до / после | MemUsage до / после |
|
||||
| --- | --- | --- |
|
||||
| API | 280,69% / 213,82% | 140,30 / 19,36 MiB |
|
||||
| PostgreSQL | 5,44% / 5,44% | 52,64 / 48,31 MiB |
|
||||
| Redis | 1,97% / 1,84% | 11,29 / 11,21 MiB |
|
||||
|
||||
Это максимумы наблюдавшихся выборок, а не точные мгновенные пики; CPU более 100% означает несколько ядер. Регистрация пользователей выполнялась перед baseline, а исправленный API использовал уже созданные записи. Поэтому различие heap/GC и памяти API нельзя приписывать singleflight.
|
||||
|
||||
Сводные исходные данные:
|
||||
|
||||
- [summary.json](evidence/cache-stampede/summary.json): параметры, образы, SQL-снимки и разности, перцентили по группам, batch RPS, выборки ресурсов и функциональные checks.
|
||||
- [requests.csv](evidence/cache-stampede/requests.csv): 1016 GET основного сравнения и дополнительных наплывов, включая 8 ожидаемых 404; все ответы признаны корректными.
|
||||
- [api.log](evidence/cache-stampede/api.log): выбранные события кэша и состояния контейнеров.
|
||||
- [Первый сценарий: CSV](evidence/redis-cache-requests.csv) и [журнал](evidence/redis-cache-api.log).
|
||||
|
||||
Batch RPS в JSON учитывает время завершения группы и исключает подготовку и паузы. Он не является измерением устойчивой производительности открытого потока запросов. Пароли, Bearer-токены и ответы создания сессий в материалы не включались.
|
||||
|
||||
### 4.4. Дополнительные сценарии и границы восстановления
|
||||
|
||||
| Воздействие / сценарий | Ожидаемое поведение | Фактический результат | Границы вывода |
|
||||
| --- | --- | --- | --- |
|
||||
| TODO | TODO | TODO | TODO |
|
||||
| Смешанный холодный наплыв: два участника и посторонний | 200 участникам, 404 постороннему | 12 GET, 3 SELECT чата, 12 SELECT сессии; все статусы корректны | Ключ singleflight включает пользователя, поэтому общее чтение не одно для всех пользователей |
|
||||
| Та же группа с заполненным кэшем | Те же права без чтения чата из БД | 12 GET, 0 SELECT чата | Проверки сессий остаются |
|
||||
| Отмена первого клиента во время заблокированного SELECT | Остальные клиенты продолжают общую загрузку | Следующий клиент получил 200 за 104,652 мс; один SELECT чата на два запроса | Проверена отмена инициатора, не все возможные сетевые отказы |
|
||||
| POST сообщения → GET другим участником | Подтверждённое сообщение сразу видно | POST — 201; следующий GET — 200, ID сообщения найден | Одна API-реплика, история читается из PostgreSQL |
|
||||
| Остановка Redis на исправленной версии | Доступ к чату через PostgreSQL | GET — 200 за 62,674 мс | Docker DNS вернул ошибку подключения; сетевой blackhole не моделировался |
|
||||
| Запуск Redis с прежним volume | Возобновление кэша без рестарта API | `EXISTS` до/после — 1/1; GET — 200 за 48,701 мс; ID контейнера API не изменился | 48,701 мс — длительность GET после готовности, а не RTO Redis |
|
||||
| Чтение истории после Redis restart | Сессия и подтверждённое сообщение сохранены | Прежняя сессия дала 200, ID сообщения найден | PostgreSQL в этом сценарии не перезапускался |
|
||||
| DEL тестового ключа после восстановления | Защищённое заполнение пустого кэша | 32 GET, один SELECT чата, 32 SELECT сессии, ошибок нет | Действует для одного пользователя внутри одной API-реплики |
|
||||
| Пересоздание API при остановленном Redis | Запуск без необязательной зависимости | На предшествующей версии GET — 200 за 72,418 мс, startup warning записан | Результат отдельно идентифицирован в первом эксперименте |
|
||||
| Отказ PostgreSQL | Отказ обязательного пути без обхода аутентификации | Не проверено | Readiness сейчас не обнаруживает такой отказ; гарантированный RTO не установлен |
|
||||
| Полный рестарт всех хранилищ, потеря хоста или диска | Проверка durability и восстановления | Не проверено | RPO/RTO и backup → restore не измерены |
|
||||
|
||||
## Ограничения и следующие шаги
|
||||
Оба эксперимента завершились с работающими API, PostgreSQL и Redis; итоговые healthy-состояния записаны в приложенных журналах. Это наблюдение на момент эксперимента, а не текущая непрерывная гарантия доступности. Обязательные данные и volumes не удалялись. Синтетические учётные записи и данные экспериментов остаются на локальном стенде.
|
||||
|
||||
TODO: какие отказы выдерживаются и какие нет; что не реализовано; где учебное упрощение; какое улучшение подтверждено, а какое пока гипотеза.
|
||||
## 5. Ограничения и дальнейшая работа
|
||||
|
||||
Реализован и измерен выбранный трек cache stampede, но полный набор требований лабораторной пока не доказан. Для завершения приёмки необходимо отдельно получить результаты публичного smoke, полного persistence-hook, отрицательных сценариев аутентификации, гонки username, rollback и EXPLAIN на требуемом объёме истории.
|
||||
|
||||
Известные расхождения реализации и конфигурации:
|
||||
|
||||
1. Поддержка `SESSION_TTL_SECONDS` отсутствует; срок session JWT задаётся другой переменной. Это нужно привести к контракту и проверить короткое expiry вместе с logout и неверным паролем.
|
||||
2. `POSTGRES_MAX_CONNECTIONS` не управляет пулом из-за отсутствующего метода конфигурационного интерфейса. Требуется связать параметр с `pgxpool.MaxConns` и отдельно определить SQL deadlines. Таймаут HTTP-записи не заменяет таймаут SQL.
|
||||
3. Readiness отражает только состояние HTTP-сервера. Нужна проверка обязательного пути PostgreSQL, сохраняющая необязательность Redis.
|
||||
4. Singleflight действует только внутри одного процесса и для одной пары «чат + пользователь». Для нескольких реплик или большого числа разных пользователей понадобятся дополнительные решения и новые замеры.
|
||||
5. Кэш чатов не имеет TTL и инвалидации. Для будущего изменения членства нужно определить обновление или удаление ключа до использования этой функции.
|
||||
6. В примере окружения остались устаревшие сведения о миграциях и неиспользуемые настройки. При текущей работе исправлен только отчёт; приложение и конфигурационные файлы не менялись.
|
||||
7. Локальный HTTP и соединение PostgreSQL с `sslmode=disable` относятся к учебному стенду. TLS, HA БД, резервное копирование и восстановление, а также потеря хоста здесь не исследовались.
|
||||
|
||||
Доказанная экономия SQL не устраняет обращения в PostgreSQL и bcrypt-проверку сессии на каждом запросе. При отказе PostgreSQL даже заполненный Redis не обеспечивает независимую работу авторизованного API. AOF Redis сохраняет кэш при исследованном корректном рестарте, но не заменяет backup PostgreSQL и не определяет RPO всего приложения.
|
||||
|
||||
## 6. Источники и материалы
|
||||
|
||||
- [Задание и критерии](README.md), [семантика API](contracts/README.md), [OpenAPI](contracts/openapi.json), [описание публичных проверок](tests/README.md).
|
||||
- [Dockerfile](Dockerfile), [Compose](docker-compose.yml), [пример окружения](.env.example), [список зависимостей](service/go.mod).
|
||||
- [Эксперимент кэша и отказа Redis](evidence/redis-cache.md), [эксперимент stampede](evidence/cache-stampede/README.md), [скрипт воспроизведения](scripts/cache_stampede.py).
|
||||
- [singleflight v0.23.0](https://pkg.go.dev/golang.org/x/sync@v0.23.0/singleflight), [PostgreSQL 17: pg_stat_statements](https://www.postgresql.org/docs/17/pgstatstatements.html).
|
||||
- [Redis: использование go-redis](https://redis.io/docs/latest/develop/clients/go/produsage/), [Redis INFO](https://redis.io/docs/latest/commands/info/).
|
||||
|
||||
При оформлении отчёта использованы исходники и уже сохранённые результаты; приложение и экспериментальные материалы не изменялись. Авторские данные и ссылка на PR не выдумывались. Проверки документа ограничены существованием локальных ссылок, соответствием чисел JSON/CSV, отсутствием незаполненных шаблонных пометок и `git diff --check`.
|
||||
|
||||
@@ -0,0 +1,95 @@
|
||||
services:
|
||||
api:
|
||||
build:
|
||||
context: .
|
||||
dockerfile: Dockerfile
|
||||
container_name: api
|
||||
image: mtusi-messenger:lab2
|
||||
restart: unless-stopped
|
||||
environment:
|
||||
APP_ENABLED: "true"
|
||||
APP_HOST: ${APP_HOST:-0.0.0.0}
|
||||
APP_PORT: ${APP_PORT:-8080}
|
||||
APP_READ_TIMEOUT: ${APP_READ_TIMEOUT:-5s}
|
||||
APP_WRITE_TIMEOUT: ${APP_WRITE_TIMEOUT:-10s}
|
||||
APP_IDLE_TIMEOUT: ${APP_IDLE_TIMEOUT:-60s}
|
||||
APP_SHUTDOWN_TIMEOUT: ${APP_SHUTDOWN_TIMEOUT:-8s}
|
||||
APPLICATION_LOG_LEVEL: ${APPLICATION_LOG_LEVEL:-info}
|
||||
APPLICATION_ENVIRONMENT: ${APPLICATION_ENVIRONMENT:-dev}
|
||||
APPLICATION_SHUTDOWN_TIMEOUT: ${APPLICATION_SHUTDOWN_TIMEOUT:-8s}
|
||||
APPLICATION_REQUEST_RATE_LIMIT: ${APPLICATION_REQUEST_RATE_LIMIT:-100}
|
||||
APPLICATION_BURST_RATE_LIMIT: ${APPLICATION_BURST_RATE_LIMIT:-100}
|
||||
APPLICATION_RATE_LIMIT_TTL: ${APPLICATION_RATE_LIMIT_TTL:-1m}
|
||||
POSTGRES_HOST: ${POSTGRES_HOST:-postgres}
|
||||
POSTGRES_PORT: ${POSTGRES_PORT:-5432}
|
||||
POSTGRES_USER: ${POSTGRES_USER:-messenger}
|
||||
POSTGRES_PASSWORD: ${POSTGRES_PASSWORD:?Set POSTGRES_PASSWORD in .env}
|
||||
POSTGRES_DATABASE: ${POSTGRES_DATABASE:-messenger}
|
||||
POSTGRES_VERSION_TABLE: ${POSTGRES_VERSION_TABLE:-versions}
|
||||
POSTGRES_RUN_MIGRATIONS: ${POSTGRES_RUN_MIGRATIONS:-true}
|
||||
POSTGRES_MAX_CONNECTIONS: ${POSTGRES_MAX_CONNECTIONS:-10}
|
||||
REDIS_HOST: ${REDIS_HOST:-redis}
|
||||
REDIS_PORT: ${REDIS_PORT:-6379}
|
||||
REDIS_USERNAME: ${REDIS_USERNAME:-default}
|
||||
REDIS_PASSWORD: ${REDIS_PASSWORD:?Set REDIS_PASSWORD in .env}
|
||||
REDIS_DB: ${REDIS_DB:-0}
|
||||
JWT_ACCESS_TOKEN_LIFETIME: ${JWT_ACCESS_TOKEN_LIFETIME:-15m}
|
||||
JWT_REFRESH_TOKEN_LIFETIME: ${JWT_REFRESH_TOKEN_LIFETIME:-24h}
|
||||
JWT_PUBLIC_KEY_PATH: ${JWT_PUBLIC_KEY_PATH:-/run/certs/public_key.pem}
|
||||
JWT_PRIVATE_KEY_PATH: ${JWT_PRIVATE_KEY_PATH:-/run/certs/private_key.pem}
|
||||
depends_on:
|
||||
postgres:
|
||||
condition: service_healthy
|
||||
volumes:
|
||||
- type: bind
|
||||
source: ./certs
|
||||
target: /run/certs
|
||||
read_only: true
|
||||
bind:
|
||||
create_host_path: false
|
||||
ports:
|
||||
- "127.0.0.1:${HOST_PORT:-8080}:8080"
|
||||
stop_grace_period: 10s
|
||||
|
||||
postgres:
|
||||
image: postgres:17.11-alpine3.23
|
||||
restart: unless-stopped
|
||||
environment:
|
||||
POSTGRES_USER: ${POSTGRES_USER:-messenger}
|
||||
POSTGRES_PASSWORD: ${POSTGRES_PASSWORD:?Set POSTGRES_PASSWORD in .env}
|
||||
POSTGRES_DB: ${POSTGRES_DATABASE:-messenger}
|
||||
volumes:
|
||||
- postgres_data:/var/lib/postgresql/data
|
||||
healthcheck:
|
||||
test: [ "CMD-SHELL", "pg_isready -h 127.0.0.1 -U \"$${POSTGRES_USER}\" -d \"$${POSTGRES_DB}\"" ]
|
||||
interval: 5s
|
||||
timeout: 3s
|
||||
start_period: 30s
|
||||
retries: 12
|
||||
stop_grace_period: 60s
|
||||
|
||||
|
||||
redis:
|
||||
image: redis:8.2.11-alpine3.22
|
||||
restart: unless-stopped
|
||||
environment:
|
||||
REDIS_PASSWORD: ${REDIS_PASSWORD:?Set REDIS_PASSWORD in .env}
|
||||
# Redis does not apply REDIS_PASSWORD by itself. Re-enter its entrypoint
|
||||
# with redis-server so it also drops privileges to the redis user.
|
||||
command:
|
||||
- sh
|
||||
- -c
|
||||
- exec docker-entrypoint.sh redis-server --appendonly yes --appendfsync everysec --requirepass "$$REDIS_PASSWORD"
|
||||
volumes:
|
||||
- redis_data:/data
|
||||
healthcheck:
|
||||
test: [ "CMD-SHELL", "REDISCLI_AUTH=\"$${REDIS_PASSWORD}\" redis-cli --no-auth-warning ping | grep -qx PONG" ]
|
||||
interval: 5s
|
||||
timeout: 3s
|
||||
start_period: 5s
|
||||
retries: 12
|
||||
stop_grace_period: 30s
|
||||
|
||||
volumes:
|
||||
postgres_data:
|
||||
redis_data:
|
||||
@@ -3,3 +3,9 @@
|
||||
Храните небольшие обезличенные результаты: команды и stdout проверок, JSON/CSV агрегатов нагрузки, EXPLAIN, dashboard JSON, текст разбора отказа. Укажите дату, commit, аппаратные лимиты и профиль нагрузки.
|
||||
|
||||
Не добавляйте .env, session tokens, cookies, приватные ключи, credentials, реальные сообщения, raw dumps и signed URLs. Для скриншотов скрывайте секреты. Большие логи/бинарные traces сохраняйте отдельно по правилам преподавателя; одного скриншота без методики недостаточно.
|
||||
|
||||
## Выполненные проверки
|
||||
|
||||
- [Кэш чатов и отказ Redis](redis-cache.md): экономия чтения чата, проверка доступа, запуск API без Redis и восстановление кэша; журнал и CSV приложены.
|
||||
|
||||
- [Cache stampede: эксперимент до/после](cache-stampede/README.md): SQL-статистика PostgreSQL, задержки, защита singleflight, read-after-write и рестарт Redis.
|
||||
|
||||
@@ -0,0 +1,121 @@
|
||||
# Cache stampede: воспроизведение, исправление и сравнение
|
||||
|
||||
## Результат и гипотеза
|
||||
|
||||
При одновременном GET одного чата несколько запросов видят пустой Redis и независимо выполняют один и тот же SELECT PostgreSQL. Гипотеза: объединение таких загрузок через singleflight сократит число SQL-запросов чтения чата до одного на наплыв одного пользователя.
|
||||
|
||||
В завершённом сравнении **308 SELECT чата до исправления → 10 после** для одинаковых 10 наплывов по 32 GET: снижение на 96.75%, в среднем 30.8 → 1.0 SELECT на наплыв. До исправления получалось 27–32 чтения на наплыв, после — ровно одно в каждом из 10 прогонов.
|
||||
|
||||
Проверки сессий отдельно выполнили 320 SELECT в каждой серии. С учётом этих двух видов SELECT общее число уменьшилось с 628 до 330, на 47.45%. Это измерения `pg_stat_statements`, а не оценка по числу HTTP-запросов или логов.
|
||||
|
||||
## Стенд и идентификация
|
||||
|
||||
- Время: 2026-11-06T09:49:37.903672Z — 2026-11-06T09:50:20.072991Z UTC (Москва UTC+3).
|
||||
- Базовый commit: `8d44c745358f131ac2836ac05153af687bcf6bc0`; проверялось изменённое рабочее дерево с ранее незакоммиченными изменениями пользователя. Этот commit сам по себе не содержит проверяемую реализацию.
|
||||
- Baseline image ID: `sha256:9c289d3a5a1043411647917239ec36394a5950203d03bb2c40e8dc1ff59da9cc`.
|
||||
- Fixed image ID: `sha256:98776dbb15c7e0b2827a1fb96ac04a96dc48dd584a1076f71847b80cb36bc332`.
|
||||
- Docker Engine 29.7.2; linux/aarch64 CPUs=14 memory_bytes=8320954368. Docker VM имеет примерно 7,75 GiB памяти; отдельных лимитов CPU/RAM у сервисов нет. Одна API-реплика; Go 1.27.2 в Dockerfile; PostgreSQL 17.11, Redis 8.2.11, go-redis v9.23.0, golang.org/x/sync v0.23.0.
|
||||
- Тестовый чат: `f6da90da-8c90-4044-b1f6-29d41b5081c0`. Один новый чат с двумя синтетическими участниками; третий пользователь в него не входит. Создано одно синтетическое сообщение. Существующие пользовательские данные не удалялись; экспериментальные записи остаются в PostgreSQL.
|
||||
|
||||
SHA-256 исходника сервиса, go.mod и скрипта, параметры запуска и ограничения контейнера сохранены в [summary.json](summary.json). До/после использовались те же чат, пользователи и сессии. Для сбора SQL-статистики PostgreSQL временно запускался с `shared_preload_libraries=pg_stat_statements`; расширение отсутствовало до эксперимента и было создано только на время измерения.
|
||||
|
||||
## Изменение реализации
|
||||
|
||||
В `GetForMember` быстрый путь Redis сохранён. На промахе запросы объединяются `singleflight.Group.DoChan` по ключу `(ChatID, UserID)`. SQL `GetForMember` зависит от пользователя, поэтому объединять его результаты только по ChatID нельзя: отказ постороннего мог бы попасть участнику.
|
||||
|
||||
Внутри общей загрузки Redis проверяется повторно, затем при необходимости читается PostgreSQL и заполняется кэш. Каждый ожидающий запрос учитывает собственную отмену; общая загрузка использует `context.WithoutCancel` и отдельный таймаут 2 секунды. Отмена первого клиента не срывает загрузку для остальных. Перед возвратом проверяется `MemberIDs`. Ошибки загрузки не сохраняются после завершения singleflight; ошибки Redis по-прежнему обходятся через PostgreSQL. Таймауты Redis из предыдущей работы сохранены.
|
||||
|
||||
HTTP-контракт и SQL-схема приложения не менялись. Модуль x/sync уже был в зависимостях; версия не обновлялась. Точная разница с baseline сохранена в [singleflight.patch](singleflight.patch).
|
||||
|
||||
## Повторяемая методика
|
||||
|
||||
Запускать на локальном стенде без постороннего трафика. Требуются Docker Compose, Python 3.9+ и подготовленные `.env` и сертификаты по инструкции проекта. Скрипт создаёт синтетические учётные записи; пароли и Bearer-токены остаются только в памяти и не попадают в файлы или аргументы процессов.
|
||||
|
||||
Для повторного сравнения из итогового исходного дерева сначала подготовить baseline в отдельной временной копии. Обратный patch применяется только в копии:
|
||||
|
||||
```sh
|
||||
baseline_dir=$(mktemp -d)
|
||||
tar --exclude='.git' --exclude='.env*' --exclude='certs' --exclude='.venv' \
|
||||
-cf - . | tar -xf - -C "$baseline_dir"
|
||||
(cd "$baseline_dir" && git apply --reverse evidence/cache-stampede/singleflight.patch)
|
||||
docker build -t mtusi-messenger:stampede-before "$baseline_dir"
|
||||
docker compose --env-file .env build api
|
||||
docker image tag mtusi-messenger:lab2 mtusi-messenger:stampede-after
|
||||
docker compose --env-file .env up -d --no-build
|
||||
python3 scripts/cache_stampede.py \
|
||||
--before-image mtusi-messenger:stampede-before \
|
||||
--after-image mtusi-messenger:stampede-after \
|
||||
--concurrency 32 --repetitions 10 --lock-ms 200
|
||||
```
|
||||
|
||||
Скрипт временно включает pg_stat_statements через отдельный Compose override в системном временном каталоге и переключает образы API без изменения основного Compose. Перезапуск PostgreSQL сохраняет volume. Глобальный сброс SQL-статистики не используется: для каждого прогона снимаются значения `calls` до и после отдельно для SELECT чата и SELECT сессии, с фильтром по БД и нормализованной форме запроса. Значения параметров SQL не выгружаются. Снимки, query IDs и разности находятся в JSON. Диагностические `chat_db_lookup` в журнале служат дополнительным подтверждением.
|
||||
|
||||
Перед каждым холодным прогоном удаляется только `chat:<экспериментальный ChatID>` в настроенной Redis DB. Все 32 потока сначала обращаются к `/health/live`, затем ожидают общего барьера. Отдельная транзакция предварительно получает `LOCK TABLE chats IN ACCESS EXCLUSIVE MODE`; через 200 мс после барьера выполняется ROLLBACK. Это моделирует медленное чтение чатов и делает одновременные промахи воспроизводимыми. Session SELECT таблицу `chats` не использует. Блокировка освобождается в `finally`; дополнительно действует пятисекундный `idle_in_transaction_session_timeout`.
|
||||
|
||||
Блокировка относится ко всей таблице `chats`, а не только к тестовому чату: во время этих коротких окон прочие операции с этой таблицей также будут ждать. Поэтому методика предназначена для локального стенда. В приложение искусственные задержки не добавлены.
|
||||
|
||||
Для каждого образа выполнены 10 холодных наплывов по 32 GET и 5 тёплых наплывов по 32 GET без блокировки. Между группами выдерживается пауза 300 мс; создание пользователей, переключение образа, сбор статистики и паузы не входят в длительность HTTP-запросов. Часы клиента монотонные; HTTP timeout — 5 секунд. Все 200-ответы сравнены с полным объектом созданного чата.
|
||||
|
||||
## SQL и задержки до/после
|
||||
|
||||
Перцентили ниже вычислены методом ближайшего ранга по всем запросам соответствующей серии; это не среднее перцентилей отдельных прогонов. Основная таблица исключает дополнительные функциональные сценарии и прогон после рестарта Redis.
|
||||
|
||||
| Версия и режим | Прогоны / GET | SELECT чата | SELECT сессии | p50 / p95 / p99, мс | Ошибки |
|
||||
| --- | --- | --- | --- | --- | --- |
|
||||
| До: пустой кэш, 200 мс | 10 / 320 | 308 | 320 | 208.124 / 215.502 / 260.385 | 0 |
|
||||
| До: заполненный кэш | 5 / 160 | 0 | 160 | 138.915 / 161.038 / 172.568 | 0 |
|
||||
| После: пустой кэш, 200 мс | 10 / 320 | 10 | 320 | 207.056 / 209.568 / 210.032 | 0 |
|
||||
| После: заполненный кэш | 5 / 160 | 0 | 160 | 136.467 / 172.304 / 200.266 | 0 |
|
||||
|
||||
Полные длительности, статусы, корректность ответов и request IDs находятся в [requests.csv](requests.csv); по каждому наплыву JSON содержит перцентили, время завершения группы и successful batch RPS. Batch RPS не учитывает паузы и подготовку и не является доказательством устойчивой пропускной способности.
|
||||
|
||||
В холодной серии p50 почти одинаков: основную задержку задаёт общее ожидание блокировки. p99 в этом запуске уменьшился с 260,385 до 210,032 мс, однако один порядок запуска «до → после» не доказывает устойчивое ускорение. У тёплой серии p95 вырос с 161,038 до 172,304 мс, хотя SQL чтения чата в обеих версиях равен нулю. Нагрузка проверок сессии, включая bcrypt-проверку токена, осталась; шум и порядок запуска не контролировались отдельными случайными перестановками. Надёжный результат эксперимента — подавление дублирующихся SELECT чата, а не универсальное сокращение задержки каждого запроса.
|
||||
|
||||
### Ресурсы
|
||||
|
||||
`docker stats --no-stream` собирался параллельно одинаково для обеих фаз. Ниже максимальные **наблюдавшиеся значения выборки**; CPU более 100% означает использование нескольких ядер. Выборка включает холодные и тёплые серии и интервалы между ними, это не точный мгновенный пик.
|
||||
|
||||
| Фаза | Контейнер | Выборок | Максимум CPU | Максимум MemUsage |
|
||||
| --- | --- | --- | --- | --- |
|
||||
| До | api | 8 | 280.69% | 140.30 MiB |
|
||||
| До | mtusi2026lab2-postgres-1 | 8 | 5.44% | 52.64 MiB |
|
||||
| До | mtusi2026lab2-redis-1 | 8 | 1.97% | 11.29 MiB |
|
||||
| После | api | 8 | 213.82% | 19.36 MiB |
|
||||
| После | mtusi2026lab2-postgres-1 | 8 | 5.44% | 48.31 MiB |
|
||||
| После | mtusi2026lab2-redis-1 | 8 | 1.84% | 11.21 MiB |
|
||||
|
||||
У baseline перед замерами регистрировались пользователи, тогда как после переключения на исправленную версию использовались готовые данные. Поэтому различие занятой памяти API нельзя приписать singleflight: подготовка, состояние heap и GC различаются. Значения приведены для описания условий, без вывода об экономии RAM.
|
||||
|
||||
## Доступ, отмена, read-after-write и рестарт
|
||||
|
||||
Дополнительный смешанный холодный наплыв: 12 запросов от двух участников и постороннего; участники получили 200, посторонний — 404, ошибок ответов нет. Выполнено 3 SELECT чата — разные пользователи имеют разные ключи singleflight. При заполненном кэше та же группа выполнила 0 SELECT чата с теми же статусами.
|
||||
|
||||
В сценарии отмены первый HTTP-клиент дошёл до заблокированного SELECT, затем его соединение было закрыто. Следующий клиент того же пользователя получил 200 после освобождения блокировки; серверная статистика показала один SELECT чата на оба запроса. Общая загрузка пережила отмену инициатора.
|
||||
|
||||
Сразу после создания чат прочитан другим участником без расхождений. После подтверждённого POST сообщения другой участник сразу прочитал историю и нашёл ID созданного сообщения. История сообщений не кэшируется; источником истины остаётся PostgreSQL.
|
||||
|
||||
При `stop redis` GET вернул 200 из PostgreSQL за 62,674 мс. После `start redis` ключ сохранился: `EXISTS` до/после вернул `1` / `1`. Это корректный stop/start с AOF и сохранённым volume, а не проверка аварийного отключения питания. ID контейнера API не изменился; прежние сессии продолжили работать. Сообщение снова найдено в истории. После удаления тестового ключа дополнительный наплыв 32 GET выполнил один SELECT чата, 32 SELECT сессии и завершился без ошибок.
|
||||
|
||||
| Проверка | HTTP | Время клиента, мс |
|
||||
| --- | --- | --- |
|
||||
| `chat_created` | 201 | 50.800 |
|
||||
| `before_chat_read_after_create` | 200 | 50.977 |
|
||||
| `after_chat_read_after_create` | 200 | 60.209 |
|
||||
| `leader_cancelled_survivor_succeeded` | 200 | 104.652 |
|
||||
| `message_committed` | 201 | 79.656 |
|
||||
| `read_after_write` | 200 | 50.551 |
|
||||
| `redis_unavailable` | 200 | 62.674 |
|
||||
| `redis_recovered` | 200 | 48.701 |
|
||||
| `message_after_restart` | 200 | 46.597 |
|
||||
|
||||
В конце скрипт удалил созданное им расширение, вернул исходный запуск PostgreSQL без preload, восстановил обычный Compose с исправленным API и запущенным Redis. `restored_preload` пуст, `extension_restored=true`; volumes не удалялись. Итоговые состояния контейнеров и диагностические записи находятся в [api.log](api.log). Логи содержат только выбранные события экспериментального чата и состояния контейнеров, без тел запросов и ответов создания сессий.
|
||||
|
||||
## Ограничения и вывод
|
||||
|
||||
Защита подавляет одновременные загрузки одинаковой пары `(ChatID, UserID)` внутри одной API-реплики. Для наплыва разных пользователей или нескольких реплик может выполняться несколько SELECT; распределённой блокировки нет. Отрицательные ответы не кэшируются. Чат хранится в Redis без TTL; обязательный API не изменяет состав участников. При добавлении таких изменений понадобится инвалидация.
|
||||
|
||||
Функциональные проверки read-after-write выполнены на имеющемся стенде с одной API-репликой, а не на многорепличной конфигурации. Данные небольшие; 200 мс созданы блокировкой, а не измерены как естественная задержка production-БД. Сравнение не оценивает предел throughput, поведение при сетевом blackhole или все требования оценки «5».
|
||||
|
||||
Сборка `go build -mod=readonly ./...` прошла локально с GOCACHE во временном каталоге и в Docker. `git diff --check` прошёл. Новые unit-тесты не добавлялись; скрипт является воспроизводимым инструментом эксперимента. Реализация и эксперимент подготовлены с помощью ИИ Codex.
|
||||
|
||||
Источники: [singleflight](https://pkg.go.dev/golang.org/x/sync@v0.23.0/singleflight), [PostgreSQL 17 pg_stat_statements](https://www.postgresql.org/docs/17/pgstatstatements.html), требования трека в [README](../../README.md), [контракт read-after-write](../../contracts/README.md).
|
||||
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,135 @@
|
||||
--- a/service/internal/service/chat/svc.go
|
||||
+++ b/service/internal/service/chat/svc.go
|
||||
@@ -11,6 +11,7 @@
|
||||
"github.com/google/uuid"
|
||||
"github.com/jackc/pgx/v5"
|
||||
"github.com/redis/go-redis/v9"
|
||||
+ "golang.org/x/sync/singleflight"
|
||||
|
||||
"gitea.privcloud.tech/mtusi2026/internal/dto"
|
||||
"gitea.privcloud.tech/mtusi2026/internal/pkg/apperr"
|
||||
@@ -18,12 +19,15 @@
|
||||
)
|
||||
|
||||
var _ API = (*Chat)(nil)
|
||||
+
|
||||
+const chatLoadTimeout = 2 * time.Second
|
||||
|
||||
type Chat struct {
|
||||
tm *txmanager.TransactionManager
|
||||
chatsRepo chatsRepo
|
||||
messagesRepo messagesRepo
|
||||
chatsCache chatsCache
|
||||
+ loads singleflight.Group
|
||||
}
|
||||
|
||||
func New(tm *txmanager.TransactionManager, chatsRepo chatsRepo, messagesRepo messagesRepo, chatsCache chatsCache) *Chat {
|
||||
@@ -72,30 +76,68 @@
|
||||
}
|
||||
|
||||
func (c *Chat) GetForMember(ctx context.Context, req dto.ChatMember) (*dto.Chat, error) {
|
||||
- chat, err := c.chatsCache.Get(ctx, req.ChatID)
|
||||
- if err == nil {
|
||||
- slog.Info("chat_cache_hit", "chat_id", req.ChatID)
|
||||
- if !slices.Contains(chat.MemberIDs, req.UserID) {
|
||||
- return nil, apperr.New(apperr.CodeNotFound, "chat not found")
|
||||
+ if err := ctx.Err(); err != nil {
|
||||
+ return nil, err
|
||||
+ }
|
||||
+ if chat, err := c.cachedChat(ctx, req.ChatID); err == nil {
|
||||
+ return chatForMember(chat, req.UserID)
|
||||
+ }
|
||||
+
|
||||
+ // Repository results depend on membership: never share a user's 404 with
|
||||
+ // another user requesting the same chat.
|
||||
+ key := req.ChatID.String() + ":" + req.UserID.String()
|
||||
+ result := c.loads.DoChan(key, func() (any, error) {
|
||||
+ // One client disconnecting must not cancel the other clients' load.
|
||||
+ loadCtx, cancel := context.WithTimeout(context.WithoutCancel(ctx), chatLoadTimeout)
|
||||
+ defer cancel()
|
||||
+
|
||||
+ // A previous load may have populated Redis after our initial miss.
|
||||
+ if chat, err := c.cachedChat(loadCtx, req.ChatID); err == nil {
|
||||
+ return chatForMember(chat, req.UserID)
|
||||
+ }
|
||||
+
|
||||
+ slog.Info("chat_db_lookup", "chat_id", req.ChatID)
|
||||
+ chat, err := c.chatsRepo.GetForMember(loadCtx, req)
|
||||
+ if err != nil {
|
||||
+ return nil, err
|
||||
+ }
|
||||
+ if err = c.chatsCache.Create(loadCtx, *chat); err != nil {
|
||||
+ slog.Warn("failed to cache chat", "chat_id", req.ChatID, "error", err)
|
||||
}
|
||||
return chat, nil
|
||||
- }
|
||||
-
|
||||
- if errors.Is(err, redis.Nil) {
|
||||
- slog.Info("chat_cache_miss", "chat_id", req.ChatID)
|
||||
- } else {
|
||||
- slog.Warn("chat_cache_read_error", "chat_id", req.ChatID, "error", err)
|
||||
- }
|
||||
-
|
||||
- slog.Info("chat_db_lookup", "chat_id", req.ChatID)
|
||||
- chat, err = c.chatsRepo.GetForMember(ctx, req)
|
||||
- if err != nil {
|
||||
- return nil, err
|
||||
- }
|
||||
- if err = c.chatsCache.Create(ctx, *chat); err != nil {
|
||||
- slog.Warn("failed to cache chat", "chat_id", req.ChatID, "error", err)
|
||||
- }
|
||||
-
|
||||
+ })
|
||||
+
|
||||
+ select {
|
||||
+ case <-ctx.Done():
|
||||
+ return nil, ctx.Err()
|
||||
+ case loaded := <-result:
|
||||
+ if err := ctx.Err(); err != nil {
|
||||
+ return nil, err
|
||||
+ }
|
||||
+ if loaded.Err != nil {
|
||||
+ return nil, loaded.Err
|
||||
+ }
|
||||
+ return chatForMember(loaded.Val.(*dto.Chat), req.UserID)
|
||||
+ }
|
||||
+}
|
||||
+
|
||||
+func (c *Chat) cachedChat(ctx context.Context, chatID uuid.UUID) (*dto.Chat, error) {
|
||||
+ chat, err := c.chatsCache.Get(ctx, chatID)
|
||||
+ switch {
|
||||
+ case err == nil:
|
||||
+ slog.Info("chat_cache_hit", "chat_id", chatID)
|
||||
+ case errors.Is(err, redis.Nil):
|
||||
+ slog.Info("chat_cache_miss", "chat_id", chatID)
|
||||
+ default:
|
||||
+ slog.Warn("chat_cache_read_error", "chat_id", chatID, "error", err)
|
||||
+ }
|
||||
+ return chat, err
|
||||
+}
|
||||
+
|
||||
+func chatForMember(chat *dto.Chat, userID uuid.UUID) (*dto.Chat, error) {
|
||||
+ if !slices.Contains(chat.MemberIDs, userID) {
|
||||
+ return nil, apperr.New(apperr.CodeNotFound, "chat not found")
|
||||
+ }
|
||||
return chat, nil
|
||||
}
|
||||
|
||||
--- a/service/go.mod
|
||||
+++ b/service/go.mod
|
||||
@@ -14,6 +14,7 @@
|
||||
github.com/spf13/viper v1.21.0
|
||||
go.uber.org/multierr v1.11.0
|
||||
golang.org/x/crypto v0.57.0
|
||||
+ golang.org/x/sync v0.23.0
|
||||
google.golang.org/grpc v1.85.0
|
||||
)
|
||||
|
||||
@@ -51,7 +52,6 @@
|
||||
github.com/vgarvardt/pgx-google-uuid/v5 v5.6.0 // indirect
|
||||
go.uber.org/atomic v1.12.0 // indirect
|
||||
go.yaml.in/yaml/v3 v3.0.5 // indirect
|
||||
- golang.org/x/sync v0.23.0 // indirect
|
||||
golang.org/x/sys v0.48.0 // indirect
|
||||
golang.org/x/text v0.42.0 // indirect
|
||||
)
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,61 @@
|
||||
|
||||
# cold_cache
|
||||
api | 2026-11-06T09:34:43.708491097Z 2026/11/06 09:34:43 INFO chat_cache_miss chat_id=cf51691d-995d-497d-a361-6d0e5685943c
|
||||
api | 2026-11-06T09:34:43.708526889Z 2026/11/06 09:34:43 INFO chat_db_lookup chat_id=cf51691d-995d-497d-a361-6d0e5685943c
|
||||
|
||||
# warm_cache
|
||||
api | 2026-11-06T09:34:43.952036889Z 2026/11/06 09:34:43 INFO chat_cache_hit chat_id=cf51691d-995d-497d-a361-6d0e5685943c
|
||||
|
||||
# outsider_warm_cache
|
||||
api | 2026-11-06T09:34:44.167119014Z 2026/11/06 09:34:44 INFO chat_cache_hit chat_id=cf51691d-995d-497d-a361-6d0e5685943c
|
||||
|
||||
# Redis stopped
|
||||
NAME IMAGE COMMAND SERVICE CREATED STATUS PORTS
|
||||
api mtusi-messenger:lab2 "/usr/local/bin/mess…" api About a minute ago Up About a minute (healthy) 127.0.0.1:8080->8080/tcp
|
||||
mtusi2026lab2-postgres-1 postgres:17.11-alpine3.23 "docker-entrypoint.s…" postgres 9 minutes ago Up 9 minutes (healthy) 5432/tcp
|
||||
mtusi2026lab2-redis-1 redis:8.2.11-alpine3.22 "docker-entrypoint.s…" redis 9 minutes ago Exited (0) Less than a second ago
|
||||
|
||||
# redis_down
|
||||
api | 2026-11-06T09:34:44.767687125Z 2026/11/06 09:34:44 WARN chat_cache_read_error chat_id=cf51691d-995d-497d-a361-6d0e5685943c error="failed to read chat cache: dial tcp: lookup redis on 127.0.0.11:53: no such host"
|
||||
api | 2026-11-06T09:34:44.767689750Z 2026/11/06 09:34:44 INFO chat_db_lookup chat_id=cf51691d-995d-497d-a361-6d0e5685943c
|
||||
api | 2026-11-06T09:34:44.770251333Z 2026/11/06 09:34:44 WARN failed to cache chat chat_id=cf51691d-995d-497d-a361-6d0e5685943c error="failed to create chat cache: dial tcp: lookup redis on 127.0.0.11:53: no such host"
|
||||
|
||||
# API recreated with Redis stopped
|
||||
api | 2026-11-06T09:34:45.388880375Z 2026/11/06 09:34:45 WARN redis unavailable at startup; continuing without cache error="dial tcp: lookup redis on 127.0.0.11:53: no such host"
|
||||
api | 2026-11-06T09:34:45.388881917Z 2026/11/06 09:34:45 INFO HTTP server started address=0.0.0.0:8080
|
||||
|
||||
# API ready while Redis remains stopped
|
||||
NAME IMAGE COMMAND SERVICE CREATED STATUS PORTS
|
||||
api mtusi-messenger:lab2 "/usr/local/bin/mess…" api Less than a second ago Up Less than a second (health: starting) 127.0.0.1:8080->8080/tcp
|
||||
mtusi2026lab2-postgres-1 postgres:17.11-alpine3.23 "docker-entrypoint.s…" postgres 9 minutes ago Up 9 minutes (healthy) 5432/tcp
|
||||
mtusi2026lab2-redis-1 redis:8.2.11-alpine3.22 "docker-entrypoint.s…" redis 9 minutes ago Exited (0) 1 second ago
|
||||
|
||||
# startup_without_redis
|
||||
api | 2026-11-06T09:34:46.010891250Z 2026/11/06 09:34:46 WARN chat_cache_read_error chat_id=cf51691d-995d-497d-a361-6d0e5685943c error="failed to read chat cache: dial tcp: lookup redis on 127.0.0.11:53: no such host"
|
||||
api | 2026-11-06T09:34:46.010893125Z 2026/11/06 09:34:46 INFO chat_db_lookup chat_id=cf51691d-995d-497d-a361-6d0e5685943c
|
||||
api | 2026-11-06T09:34:46.014563084Z 2026/11/06 09:34:46 WARN failed to cache chat chat_id=cf51691d-995d-497d-a361-6d0e5685943c error="failed to create chat cache: dial tcp: lookup redis on 127.0.0.11:53: no such host"
|
||||
|
||||
# redis_recovered
|
||||
api | 2026-11-06T09:34:46.555832459Z 2026/11/06 09:34:46 INFO chat_cache_hit chat_id=cf51691d-995d-497d-a361-6d0e5685943c
|
||||
|
||||
# recovery_cold_cache
|
||||
api | 2026-11-06T09:34:46.884677792Z 2026/11/06 09:34:46 INFO chat_cache_miss chat_id=cf51691d-995d-497d-a361-6d0e5685943c
|
||||
api | 2026-11-06T09:34:46.884696959Z 2026/11/06 09:34:46 INFO chat_db_lookup chat_id=cf51691d-995d-497d-a361-6d0e5685943c
|
||||
|
||||
# recovery_warm_cache
|
||||
api | 2026-11-06T09:34:47.112979084Z 2026/11/06 09:34:47 INFO chat_cache_hit chat_id=cf51691d-995d-497d-a361-6d0e5685943c
|
||||
|
||||
# recovery_outsider
|
||||
api | 2026-11-06T09:34:47.354961709Z 2026/11/06 09:34:47 INFO chat_cache_hit chat_id=cf51691d-995d-497d-a361-6d0e5685943c
|
||||
|
||||
# Final container state
|
||||
NAME IMAGE COMMAND SERVICE CREATED STATUS PORTS
|
||||
api mtusi-messenger:lab2 "/usr/local/bin/mess…" api 2 seconds ago Up 2 seconds (health: starting) 127.0.0.1:8080->8080/tcp
|
||||
mtusi2026lab2-postgres-1 postgres:17.11-alpine3.23 "docker-entrypoint.s…" postgres 9 minutes ago Up 9 minutes (healthy) 5432/tcp
|
||||
mtusi2026lab2-redis-1 redis:8.2.11-alpine3.22 "docker-entrypoint.s…" redis 9 minutes ago Up 1 second (health: starting) 6379/tcp
|
||||
|
||||
# Final health checks settled
|
||||
NAME IMAGE COMMAND SERVICE CREATED STATUS PORTS
|
||||
api mtusi-messenger:lab2 "/usr/local/bin/mess…" api 2 minutes ago Up 2 minutes (healthy) 127.0.0.1:8080->8080/tcp
|
||||
mtusi2026lab2-postgres-1 postgres:17.11-alpine3.23 "docker-entrypoint.s…" postgres 11 minutes ago Up 11 minutes (healthy) 5432/tcp
|
||||
mtusi2026lab2-redis-1 redis:8.2.11-alpine3.22 "docker-entrypoint.s…" redis 11 minutes ago Up 2 minutes (healthy) 6379/tcp
|
||||
@@ -0,0 +1,10 @@
|
||||
stage,timestamp_utc,actor,status,duration_ms,request_id
|
||||
cold_cache,2026-11-06T09:34:43.658980Z,alice,200,52.955,bc83a4a8-d946-4a47-bf56-2fa665bd0656
|
||||
warm_cache,2026-11-06T09:34:43.892999Z,alice,200,60.433,cbc53e92-06d6-4929-9ec8-95d285ad2c49
|
||||
outsider_warm_cache,2026-11-06T09:34:44.118562Z,eve,404,50.171,7b97fcb4-7144-4856-a06b-bfecf5408ca4
|
||||
redis_down,2026-11-06T09:34:44.714879Z,alice,200,56.076,e08e99da-70a6-4cf4-865b-b86885e40dcf
|
||||
startup_without_redis,2026-11-06T09:34:45.942892Z,alice,200,72.418,ad8653e4-1f7c-482a-a475-f4b34ed9235c
|
||||
redis_recovered,2026-11-06T09:34:46.508318Z,alice,200,48.239,e7661654-9218-48d5-9056-d64f36ee477b
|
||||
recovery_cold_cache,2026-11-06T09:34:46.828222Z,alice,200,57.662,6799b337-7c13-486c-a53f-7c93d8ef7dea
|
||||
recovery_warm_cache,2026-11-06T09:34:47.052792Z,alice,200,60.97,17c00939-9b2a-4d49-bf7f-3e47807772e7
|
||||
recovery_outsider,2026-11-06T09:34:47.291011Z,eve,404,64.866,0919aec6-9e42-47c0-879f-4cf09ccb836d
|
||||
|
@@ -0,0 +1,89 @@
|
||||
# Кэш чатов: экономия SQL и отказ Redis
|
||||
|
||||
## Условия и изменения
|
||||
|
||||
Эксперимент выполнен 2026-11-06T09:34:40.942506Z — 2026-11-06T09:34:47.751055Z (UTC, Москва UTC+3).
|
||||
Базовый commit: `8d44c745358f131ac2836ac05153af687bcf6bc0`. Проверялась сборка из изменённого рабочего дерева, включая ранее незакоммиченные изменения пользователя; этот commit сам по себе не содержит проверенную реализацию.
|
||||
API image ID: `sha256:9d4af3c2a5c8209475eb195bf04598b843208527f7278af64326fcc4fd7423ec`.
|
||||
|
||||
Стенд: Docker Engine 29.7.2, linux/aarch64; CPUs=14; memory_bytes=8320954368; доступно примерно 7,75 GiB памяти Docker VM. У API, PostgreSQL и Redis отдельные ограничения CPU/RAM не заданы (`Memory=0`, `NanoCpus=0`, `CpuQuota=0`, `CpuPeriod=0`). Redis 8.2.11, PostgreSQL image `postgres:17.11-alpine3.23`, сборка контейнера Go 1.27.2, локально `go version go1.27.0 darwin/arm64`. go-redis v9.23.0.
|
||||
|
||||
В `GetForMember` оставлены Info-события `chat_cache_hit`, `chat_cache_miss`, `chat_db_lookup`. `errors.Is(err, redis.Nil)` отличает обычный промах от ошибки чтения `chat_cache_read_error` уровня Warn. Проверка `MemberIDs` выполняется до возврата кэшированного чата. Ошибки чтения и записи Redis не мешают получить чат из PostgreSQL.
|
||||
|
||||
Стартовый PING Redis больше не останавливает приложение при ошибке; зависимость API от Redis в Compose удалена. PostgreSQL остаётся обязательной зависимостью. В go-redis установлены `DialTimeout`, `ReadTimeout`, `WriteTimeout`, `PoolTimeout` по 200 мс; `MaxRetries=-1`, `DialerRetries=1`, `ContextTimeoutEnabled=true`. Каждый GET/SET кэша и стартовый PING получает отдельный дочерний контекст с бюджетом 300 мс. Контекст обращения к PostgreSQL остаётся исходным. При GET и последующем SET возможны два отдельных бюджета кэша; это не общий таймаут всего HTTP-запроса.
|
||||
|
||||
## Методика и команды
|
||||
|
||||
Перед экспериментом успешно выполнены `go build ./...` из `service/`, `docker compose --env-file .env config --quiet` и `docker compose --env-file .env up -d --build api redis`. Новые тесты не добавлялись.
|
||||
|
||||
Через API зарегистрированы три уникальных синтетических пользователя alice, bob и eve. Через `POST /api/v1/auth/sessions` с Basic-аутентификацией получены действующие Bearer session tokens. В этом API используется поле `token` ответа создания сессии. Создан один чат с alice и bob; eve в него не входит. Пароли и токены хранились только в памяти процесса проверки; ответы создания сессий не сохранялись. Созданные пользователи и чат остались на локальном стенде.
|
||||
|
||||
Тестовый чат: `cf51691d-995d-497d-a361-6d0e5685943c`. Redis DB: `0`, ключ: `chat:cf51691d-995d-497d-a361-6d0e5685943c`.
|
||||
Профиль: один последовательный поток, 9 GET одного чата, без нагрузки от экспериментального клиента параллельно. Это функциональная демонстрация, а не измерение пропускной способности или процентилей задержки.
|
||||
|
||||
Для удаления ровно одного ключа использовалась команда ниже. Пароль разворачивается внутри контейнера и не передаётся значением в аргументах хостовой команды:
|
||||
|
||||
```sh
|
||||
docker compose --env-file .env exec -T redis sh -c \
|
||||
'REDISCLI_AUTH="$REDIS_PASSWORD" exec redis-cli --no-auth-warning -n 0 DEL "$1"' \
|
||||
redis-cli chat:cf51691d-995d-497d-a361-6d0e5685943c
|
||||
```
|
||||
|
||||
Первый DEL вернул `0`: новый чат ещё не был закэширован. Затем выполнены два GET участником и один GET посторонним. Запросы имели вид:
|
||||
|
||||
```sh
|
||||
curl -sS -D - -o /dev/null \
|
||||
-H "Authorization: Bearer $SESSION_TOKEN" \
|
||||
http://127.0.0.1:8080/api/v1/chats/cf51691d-995d-497d-a361-6d0e5685943c
|
||||
```
|
||||
|
||||
`SESSION_TOKEN` здесь — локальная переменная с действующей сессией нужного пользователя; её значение не включается в отчёт. Реальный прогон выполнялся HTTP-клиентом Python с таймаутом 5 секунд и замером через монотонные часы. У каждого ответа записаны статус, длительность и `X-Request-Id`. Все успешные ответы GET сравнены с полным объектом созданного чата, расхождений нет.
|
||||
|
||||
Затем выполнена последовательность:
|
||||
|
||||
```sh
|
||||
docker compose --env-file .env stop redis
|
||||
# GET участником: 200 из PostgreSQL.
|
||||
docker compose --env-file .env up -d --no-deps --force-recreate api
|
||||
# /health/ready: 200; GET прежним Bearer-токеном: 200 при остановленном Redis.
|
||||
docker compose --env-file .env start redis
|
||||
# Дождаться PONG; GET: cache hit без перезапуска API.
|
||||
# Повторить DEL одного ключа, затем два GET участником и один GET посторонним.
|
||||
docker compose --env-file .env ps -a
|
||||
```
|
||||
|
||||
До остановки `EXISTS` ключа вернул `1`, после запуска Redis — `1`. Повторный DEL вернул `1`. Ключ пережил корректный stop/start с включёнными AOF (`appendonly yes`, `appendfsync everysec`) и сохранённым volume. Это наблюдение для корректной остановки, а не доказательство сохранности при аварийном отключении питания. Удалялись только указанные тестовые ключи; volumes не удалялись.
|
||||
|
||||
## Фактические результаты
|
||||
|
||||
| Этап | HTTP | Время клиента, мс | События API |
|
||||
| --- | --- | --- | --- |
|
||||
| Пустой кэш, участник | 200 | 52.955 | miss → db_lookup |
|
||||
| Заполненный кэш, участник | 200 | 60.433 | hit, без db_lookup |
|
||||
| Заполненный кэш, посторонний | 404 | 50.171 | hit, без db_lookup |
|
||||
| Redis остановлен | 200 | 56.076 | read_error → db_lookup; ошибка SET |
|
||||
| API пересоздан без Redis | 200 | 72.418 | read_error → db_lookup; ошибка SET |
|
||||
| Redis восстановлен, API не перезапускался | 200 | 48.239 | hit, без db_lookup |
|
||||
| После восстановления и DEL | 200 | 57.662 | miss → db_lookup |
|
||||
| Повтор после заполнения | 200 | 60.97 | hit, без db_lookup |
|
||||
| Посторонний после восстановления | 404 | 64.866 | hit, без db_lookup |
|
||||
|
||||
Здесь `hit`, `miss`, `read_error`, `db_lookup` соответствуют событиям `chat_cache_hit`, `chat_cache_miss`, `chat_cache_read_error`, `chat_db_lookup`. При остановленном контейнере Docker DNS возвращал `lookup redis ... no such host`; это ошибка подключения, а не `redis.Nil`. В этих запросах зафиксированы также ошибки записи кэша, но клиент получил корректный чат.
|
||||
|
||||
При старте API без Redis записано предупреждение `redis unavailable at startup; continuing without cache`, затем `HTTP server started`. Готовность проверена через HTTP, поэтому промежуточный статус Docker `health: starting` в журнале не означает, что запросы ещё не обслуживались.
|
||||
|
||||
[CSV запросов](redis-cache-requests.csv) содержит точные времена и request IDs. [Журнал API и состояния контейнеров](redis-cache-api.log) содержит отобранные строки исходных логов по временным окнам каждого последовательного запроса. События кэша содержат `chat_id`; HTTP-статусы и request IDs взяты непосредственно из ответов и находятся в CSV. Журнал не является полным дампом логов контейнеров.
|
||||
|
||||
## Что доказано и ограничения
|
||||
|
||||
Первый GET вызывает `ChatsRepo.GetForMember`, выполняющий один SQL SELECT чата с проверкой членства. Повторный GET возвращается из Redis до вызова репозитория. Таким образом, пара GET участника выполняет **один запрос чтения чата вместо двух: один запрос сэкономлен**. После восстановления Redis это подтверждено повторно. Число вызовов установлено по диагностическим веткам кода; серверный SQL-трейс или `pg_stat_statements` в этом эксперименте не собирались.
|
||||
|
||||
Каждый авторизованный GET отдельно проверяет сессию в PostgreSQL (`VerifySession` → `refreshTokensRepo.GetByID`), включая попадание в кэш. Поэтому отсутствие `chat_db_lookup` не означает отсутствие любых SQL-запросов. Время второго запроса в этой короткой серии не уменьшилось; демонстрация подтверждает экономию чтений чата, а не ускорение HTTP.
|
||||
|
||||
Посторонний пользователь получил 404 при заполненном кэше до и после отказа. API обслуживает запросы и запускается при недоступном Redis; после восстановления Redis тот же клиент возобновляет работу. Проверялось отключение через stop, а не зависшее соединение или потеря пакетов, поэтому наблюдаемые 56–72 мс не доказывают верхнюю границу задержки для всех сетевых отказов.
|
||||
|
||||
Текущий кэш хранит чат без TTL (`SET` с expiration=0). Для существующего API без изменения состава участников это не менялось; при добавлении такого изменения потребуется инвалидация кэша, чтобы кэшированная проверка доступа не устаревала.
|
||||
|
||||
Общие `keyspace_hits`/`keyspace_misses` Redis в доказательство отдельных GET не использовались: они включают обращения других клиентов.
|
||||
|
||||
Справочники: [таймауты и повторы go-redis](https://redis.io/docs/latest/develop/clients/go/produsage/), [Redis INFO](https://redis.io/docs/latest/commands/info/), [Docker Compose stop](https://docs.docker.com/reference/cli/docker/compose/stop/), [Docker Compose start](https://docs.docker.com/reference/cli/docker/compose/start/).
|
||||
@@ -1,7 +0,0 @@
|
||||
# Инфраструктура студента
|
||||
|
||||
Здесь разместите конфигурации выбранных сервисов; основную топологию — в корневом compose.yaml/stack.yaml. `compose.example.yaml` — только worksheet ролей и намеренно не запускается. `contracts/infrastructure.json` задаёт минимальные роли, не готовые образы/пароли.
|
||||
|
||||
В REPORT.md сопоставьте роль → service name → версия/digest → health/readiness → volume → сеть/порт → способ передачи credentials. Приведите bootstrap (schema, bucket, broker topology, а с lab6 provisioning) и безопасное повторение этих команд.
|
||||
|
||||
Приложение строится из исходников. Не используйте заранее существующий образ преподавательского сервера вместо своей реализации. Restart hook перезапускает все соответствующие stores с volumes; failover hook останавливает только заданную API-реплику.
|
||||
@@ -0,0 +1,418 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Repeatable local cache experiment; uses Docker, Python stdlib and synthetic data.
|
||||
|
||||
Requires prebuilt before/after API images. Temporarily restarts local PostgreSQL
|
||||
with pg_stat_statements, then restores Compose without deleting data or volumes.
|
||||
"""
|
||||
import argparse
|
||||
import base64
|
||||
import concurrent.futures as futures
|
||||
import contextlib
|
||||
import csv
|
||||
import datetime as dt
|
||||
import http.client
|
||||
import hashlib
|
||||
import json
|
||||
import math
|
||||
import pathlib
|
||||
import secrets
|
||||
import select
|
||||
import socket
|
||||
import subprocess
|
||||
import tempfile
|
||||
import threading
|
||||
import time
|
||||
import uuid
|
||||
|
||||
ROOT = pathlib.Path(__file__).resolve().parents[1]
|
||||
NORMAL = ['docker', 'compose', '--env-file', str(ROOT / '.env'), '-f', str(ROOT / 'docker-compose.yml')]
|
||||
PSQL = ['exec', '-T', 'postgres', 'sh', '-c',
|
||||
'exec psql -X -q -At -v ON_ERROR_STOP=1 -U "$POSTGRES_USER" -d "$POSTGRES_DB"']
|
||||
|
||||
|
||||
def now():
|
||||
return dt.datetime.now(dt.timezone.utc).isoformat().replace('+00:00', 'Z')
|
||||
|
||||
|
||||
def run(args, sql=None, timeout=90):
|
||||
result = subprocess.run(args, input=sql, text=True, capture_output=True, cwd=ROOT, timeout=timeout)
|
||||
if result.returncode:
|
||||
# Never echo config, SQL parameters, HTTP bodies or credentials on failure.
|
||||
raise RuntimeError('External command failed: ' + ' '.join(args[:3]))
|
||||
return result.stdout.strip()
|
||||
|
||||
|
||||
def percentile(values, fraction):
|
||||
values = sorted(values)
|
||||
return round(values[max(0, math.ceil(len(values) * fraction) - 1)], 3)
|
||||
|
||||
|
||||
class Experiment:
|
||||
def __init__(self, args, override):
|
||||
self.args, self.override = args, override
|
||||
self.out = ROOT / args.output
|
||||
self.out.mkdir(parents=True, exist_ok=True)
|
||||
cfg = json.loads(run(NORMAL + ['config', '--format', 'json']))
|
||||
api = cfg['services']['api']
|
||||
self.port = int(api['ports'][0]['published'])
|
||||
self.db = str(api['environment']['REDIS_DB'])
|
||||
self.pg_command = cfg['services']['postgres'].get('command') or ['postgres']
|
||||
self.normal_image = api['image']
|
||||
self.requests, self.runs, self.checks, self.logs, self.resources = [], [], [], [], []
|
||||
self.summary = dict(started_utc=now(), commit=run(['git', 'rev-parse', 'HEAD']), dirty=True,
|
||||
method=vars(args).copy(), images={}, runs=self.runs, checks=self.checks, resources=self.resources)
|
||||
self.summary['docker_resources'] = run(['docker', 'info', '--format',
|
||||
'{{.OSType}}/{{.Architecture}} CPUs={{.NCPU}} memory_bytes={{.MemTotal}}'])
|
||||
self.summary['docker_version'] = run(['docker', 'version', '--format', '{{.Server.Version}}'])
|
||||
for name, image in [('before', args.before_image), ('after', args.after_image)]:
|
||||
self.summary['images'][name] = run(['docker', 'image', 'inspect', '--format', '{{.Id}}', image])
|
||||
if self.summary['images']['after'] != run(['docker', 'image', 'inspect', '--format', '{{.Id}}', self.normal_image]):
|
||||
raise RuntimeError('Build/tag the after image as the normal Compose API image before running')
|
||||
self.summary['postgres_version'] = self.sql('SHOW server_version;')
|
||||
self.summary['redis_version'] = self.redis('INFO', 'server').split('redis_version:')[1].splitlines()[0]
|
||||
self.summary['source_sha256'] = {name: hashlib.sha256((ROOT/name).read_bytes()).hexdigest() for name in ('service/internal/service/chat/svc.go','service/go.mod','scripts/cache_stampede.py')}
|
||||
self.preload = self.sql('SHOW shared_preload_libraries;')
|
||||
self.had_extension = self.sql("SELECT count(*) FROM pg_extension WHERE extname='pg_stat_statements';") == '1'
|
||||
libraries = [s.strip() for s in self.preload.split(',') if s.strip()]
|
||||
if 'pg_stat_statements' not in libraries:
|
||||
libraries.append('pg_stat_statements')
|
||||
self.libraries = ','.join(libraries)
|
||||
|
||||
def compose(self, *args):
|
||||
return run(NORMAL + ['-f', str(self.override)] + list(args))
|
||||
|
||||
def sql(self, sql):
|
||||
return run(NORMAL + PSQL, sql=sql)
|
||||
|
||||
def use_image(self, image):
|
||||
self.override.write_text(json.dumps({'services': {
|
||||
'api': {'image': image},
|
||||
'postgres': {'command': self.pg_command + ['-c', 'shared_preload_libraries=' + self.libraries]}}}))
|
||||
|
||||
def redis(self, *args):
|
||||
return run(NORMAL + ['exec', '-T', 'redis', 'sh', '-c',
|
||||
'REDISCLI_AUTH="$REDIS_PASSWORD" exec redis-cli --no-auth-warning -n "$@"',
|
||||
'redis-cli', self.db] + list(args))
|
||||
|
||||
def wait_postgres(self):
|
||||
deadline = time.monotonic() + 60
|
||||
while time.monotonic() < deadline:
|
||||
try:
|
||||
if self.sql('SELECT 1;') == '1':
|
||||
return
|
||||
except RuntimeError:
|
||||
pass
|
||||
time.sleep(.3)
|
||||
raise RuntimeError('PostgreSQL readiness timeout')
|
||||
|
||||
def http(self, method, path, actor=None, body=None, basic=None, timeout=5):
|
||||
conn = http.client.HTTPConnection('127.0.0.1', self.port, timeout=timeout)
|
||||
headers = {}
|
||||
if actor:
|
||||
headers['Authorization'] = 'Bearer ' + actor['token']
|
||||
if basic:
|
||||
headers['Authorization'] = 'Basic ' + base64.b64encode(basic.encode()).decode()
|
||||
if body is not None:
|
||||
headers['Content-Type'] = 'application/json'
|
||||
stamp, started = now(), time.perf_counter()
|
||||
try:
|
||||
conn.request(method, path, body=None if body is None else json.dumps(body), headers=headers)
|
||||
response = conn.getresponse()
|
||||
data = response.read()
|
||||
return dict(status=response.status, data=json.loads(data) if data else None,
|
||||
request_id=response.getheader('X-Request-Id', ''), timestamp_utc=stamp,
|
||||
duration_ms=round((time.perf_counter() - started) * 1000, 3))
|
||||
finally:
|
||||
conn.close()
|
||||
|
||||
def ready(self):
|
||||
deadline = time.monotonic() + 45
|
||||
while time.monotonic() < deadline:
|
||||
try:
|
||||
if self.http('GET', '/health/ready')['status'] == 200:
|
||||
return
|
||||
except (OSError, http.client.HTTPException):
|
||||
pass
|
||||
time.sleep(.3)
|
||||
raise RuntimeError('API readiness timeout')
|
||||
|
||||
def collect_logs(self, since, label):
|
||||
time.sleep(.05)
|
||||
lines = run(NORMAL + ['logs', '--no-color', '--timestamps', '--since', since, 'api'])
|
||||
safe = [line for line in lines.splitlines() if
|
||||
(self.chat['id'] in line and ('chat_cache_' in line or 'chat_db_lookup' in line or 'failed to cache chat' in line))
|
||||
or 'redis unavailable at startup' in line or 'HTTP server started' in line]
|
||||
self.logs.append('\n# ' + label + '\n' + '\n'.join(safe) + '\n')
|
||||
self.flush()
|
||||
|
||||
def flush(self):
|
||||
self.summary['updated_utc'] = now()
|
||||
(self.out / 'summary.json').write_text(json.dumps(self.summary, indent=2) + '\n')
|
||||
(self.out / 'api.log').write_text(''.join(self.logs))
|
||||
if self.requests:
|
||||
with (self.out / 'requests.csv').open('w', newline='') as stream:
|
||||
writer = csv.DictWriter(stream, fieldnames=list(self.requests[0]), lineterminator="\n")
|
||||
writer.writeheader()
|
||||
writer.writerows(self.requests)
|
||||
|
||||
def actor(self, label):
|
||||
username, password = 'stampede_' + uuid.uuid4().hex[:16], secrets.token_urlsafe(24)
|
||||
user = self.http('POST', '/api/v1/users', body=dict(username=username, display_name='Experiment ' + label, password=password))
|
||||
if user['status'] != 201:
|
||||
raise RuntimeError('Synthetic registration failed')
|
||||
session = self.http('POST', '/api/v1/auth/sessions', basic=username + ':' + password)
|
||||
if session['status'] != 201:
|
||||
raise RuntimeError('Synthetic login failed')
|
||||
return dict(label=label, id=user['data']['id'], token=session['data']['token'])
|
||||
|
||||
def snapshot(self):
|
||||
# Only normalized query identities and counters are exported, never SQL parameters.
|
||||
data = self.sql("""SELECT coalesce(json_agg(row_to_json(s)), '[]'::json) FROM (
|
||||
SELECT queryid::text AS queryid, calls, total_exec_time,
|
||||
CASE WHEN query LIKE '%FROM chats c%' THEN 'chat' ELSE 'session' END AS kind
|
||||
FROM pg_stat_statements WHERE dbid=(SELECT oid FROM pg_database WHERE datname=current_database())
|
||||
AND ((query LIKE '%FROM chats c%' AND query LIKE '%AND EXISTS%')
|
||||
OR (query LIKE '%FROM refresh_tokens%' AND query LIKE '%WHERE id = $1%' AND query NOT LIKE '%FOR UPDATE%'))
|
||||
) s;""")
|
||||
return json.loads(data)
|
||||
|
||||
@staticmethod
|
||||
def delta(before, after):
|
||||
result = {}
|
||||
for kind in ('chat', 'session'):
|
||||
result[kind + '_sql'] = sum(r['calls'] for r in after if r['kind'] == kind) - sum(r['calls'] for r in before if r['kind'] == kind)
|
||||
result[kind + '_sql_exec_ms'] = round(sum(r['total_exec_time'] for r in after if r['kind'] == kind) - sum(r['total_exec_time'] for r in before if r['kind'] == kind), 3)
|
||||
return result
|
||||
|
||||
@contextlib.contextmanager
|
||||
def lock(self):
|
||||
proc = subprocess.Popen(NORMAL + PSQL, stdin=subprocess.PIPE, stdout=subprocess.PIPE,
|
||||
stderr=subprocess.PIPE, text=True, cwd=ROOT)
|
||||
try:
|
||||
proc.stdin.write("SET statement_timeout='5s'; SET idle_in_transaction_session_timeout='5s';\nBEGIN;\nLOCK TABLE chats IN ACCESS EXCLUSIVE MODE;\n\\echo LOCKED\n")
|
||||
proc.stdin.flush()
|
||||
if not select.select([proc.stdout], [], [], 8)[0] or proc.stdout.readline().strip() != 'LOCKED':
|
||||
raise RuntimeError('Could not acquire experimental table lock')
|
||||
yield
|
||||
finally:
|
||||
if proc.poll() is None:
|
||||
try:
|
||||
proc.communicate('ROLLBACK;\n\\q\n', timeout=8)
|
||||
except (subprocess.TimeoutExpired, BrokenPipeError):
|
||||
proc.kill()
|
||||
proc.communicate()
|
||||
|
||||
def burst(self, phase, mode, repetition, actors=None):
|
||||
actors = actors or [self.alice] * self.args.concurrency
|
||||
if mode not in ('warm', 'mixed_warm'):
|
||||
self.redis('DEL', self.key)
|
||||
before, since = self.snapshot(), now()
|
||||
barrier = threading.Barrier(len(actors) + 1, timeout=15)
|
||||
path = '/api/v1/chats/' + self.chat['id']
|
||||
|
||||
def worker(index, actor):
|
||||
# Establish threads and touch HTTP before releasing the simultaneous burst.
|
||||
if self.http('GET', '/health/live')['status'] != 200:
|
||||
raise RuntimeError('Worker warmup failed')
|
||||
barrier.wait()
|
||||
try:
|
||||
result = self.http('GET', path, actor)
|
||||
expected = 404 if actor['label'] == 'eve' else 200
|
||||
ok = result['status'] == expected and (expected == 404 or result['data'] == self.chat)
|
||||
status, ms, rid, stamp = result['status'], result['duration_ms'], result['request_id'], result['timestamp_utc']
|
||||
except (OSError, http.client.HTTPException):
|
||||
ok, status, ms, rid, stamp = False, 0, 5000, '', now()
|
||||
return dict(phase=phase, mode=mode, repetition=repetition, worker=index, actor=actor['label'],
|
||||
timestamp_utc=stamp, status=status, duration_ms=ms, request_id=rid, correct=ok)
|
||||
|
||||
with futures.ThreadPoolExecutor(max_workers=len(actors)) as pool:
|
||||
jobs = [pool.submit(worker, i, actor) for i, actor in enumerate(actors)]
|
||||
controlled = mode in ('cold', 'mixed_cold')
|
||||
with self.lock() if controlled else contextlib.nullcontext():
|
||||
barrier.wait()
|
||||
started = time.perf_counter()
|
||||
if controlled:
|
||||
time.sleep(self.args.lock_ms / 1000)
|
||||
group = [job.result(timeout=10) for job in jobs]
|
||||
elapsed = time.perf_counter() - started
|
||||
after = self.snapshot()
|
||||
errors = sum(not row['correct'] for row in group)
|
||||
durations = [row['duration_ms'] for row in group]
|
||||
measured = dict(phase=phase, mode=mode, repetition=repetition, requests=len(group), errors=errors,
|
||||
elapsed_ms=round(elapsed*1000, 3), successful_rps=round((len(group)-errors)/elapsed, 3),
|
||||
latency_ms={f'p{p}': percentile(durations, p/100) for p in (50,95,99)},
|
||||
sql_before=before, sql_after=after, **self.delta(before, after))
|
||||
self.requests.extend(group)
|
||||
self.runs.append(measured)
|
||||
self.collect_logs(since, f'{phase}/{mode}/{repetition}')
|
||||
print(f'{phase}/{mode}/{repetition}: chat SQL={measured["chat_sql"]}, session SQL={measured["session_sql"]}, p95={measured["latency_ms"]["p95"]} ms, errors={errors}', flush=True)
|
||||
if errors:
|
||||
raise RuntimeError('Incorrect responses during burst')
|
||||
if mode == 'cold' and phase == 'after' and measured['chat_sql'] != 1:
|
||||
raise RuntimeError('Expected exactly one chat SELECT with singleflight')
|
||||
if mode in ('warm', 'mixed_warm') and measured['chat_sql'] != 0:
|
||||
raise RuntimeError('Warm cache unexpectedly queried chats')
|
||||
if measured['session_sql'] != len(actors):
|
||||
raise RuntimeError('Session SQL accounting differs from request count; check concurrent traffic')
|
||||
time.sleep(.3)
|
||||
|
||||
def checked(self, name, method, path, actor, body=None, status=200):
|
||||
result = self.http(method, path, actor, body)
|
||||
if result['status'] != status:
|
||||
raise RuntimeError('Functional check failed: ' + name)
|
||||
self.checks.append(dict(name=name, status=result['status'], duration_ms=result['duration_ms'], request_id=result['request_id']))
|
||||
return result['data']
|
||||
|
||||
def cancellation(self):
|
||||
self.redis('DEL', self.key)
|
||||
before, since = self.snapshot(), now()
|
||||
path = '/api/v1/chats/' + self.chat['id']
|
||||
with futures.ThreadPoolExecutor(max_workers=1) as pool:
|
||||
with self.lock():
|
||||
leader = http.client.HTTPConnection('127.0.0.1', self.port, timeout=5)
|
||||
try:
|
||||
leader.request('GET', path, headers={'Authorization': 'Bearer ' + self.alice['token']})
|
||||
deadline = time.monotonic() + 1
|
||||
while self.sql("SELECT count(*) FROM pg_stat_activity WHERE pid <> pg_backend_pid() AND wait_event_type='Lock' AND query LIKE 'SELECT c.id%';") == '0':
|
||||
if time.monotonic() > deadline:
|
||||
raise RuntimeError('Leader did not reach SQL')
|
||||
time.sleep(.01)
|
||||
leader.sock.shutdown(socket.SHUT_RDWR)
|
||||
finally:
|
||||
leader.close()
|
||||
survivor = pool.submit(self.http, 'GET', path, self.alice)
|
||||
time.sleep(.1)
|
||||
result = survivor.result(timeout=5)
|
||||
counters = self.delta(before, self.snapshot())
|
||||
if result['status'] != 200 or result['data'] != self.chat or counters['chat_sql'] != 1:
|
||||
raise RuntimeError('Client cancellation broke shared loading')
|
||||
self.checks.append(dict(name='leader_cancelled_survivor_succeeded', status=result['status'],
|
||||
request_id=result['request_id'], duration_ms=result['duration_ms'], **counters))
|
||||
self.collect_logs(since, 'Cancelled initiating client; surviving client received chat')
|
||||
|
||||
def functional(self):
|
||||
self.cancellation()
|
||||
path = '/api/v1/chats/' + self.chat['id']
|
||||
self.burst('after', 'mixed_cold', 1, [self.eve, self.alice, self.bob] * 4)
|
||||
self.burst('after', 'mixed_warm', 1, [self.eve, self.alice, self.bob] * 4)
|
||||
message = self.checked('message_committed', 'POST', path+'/messages', self.alice,
|
||||
{'text': 'Synthetic read-after-write evidence'}, status=201)
|
||||
history = self.checked('read_after_write', 'GET', path+'/messages?limit=100', self.bob)
|
||||
if message['id'] not in [item['id'] for item in history['items']]:
|
||||
raise RuntimeError('Committed message missing from following read')
|
||||
since = now()
|
||||
api_before = run(NORMAL + ['ps', '-q', 'api'])
|
||||
self.summary['key_before_restart'] = self.redis('EXISTS', self.key)
|
||||
try:
|
||||
run(NORMAL + ['stop', 'redis'])
|
||||
self.checked('redis_unavailable', 'GET', path, self.alice)
|
||||
finally:
|
||||
run(NORMAL + ['start', 'redis'])
|
||||
deadline = time.monotonic()+30
|
||||
while self.redis('PING') != 'PONG':
|
||||
if time.monotonic()>deadline:
|
||||
raise RuntimeError('Redis recovery timeout')
|
||||
time.sleep(.3)
|
||||
self.summary['key_after_restart'] = self.redis('EXISTS', self.key)
|
||||
self.checked('redis_recovered', 'GET', path, self.bob)
|
||||
history = self.checked('message_after_restart', 'GET', path+'/messages?limit=100', self.bob)
|
||||
if message['id'] not in [item['id'] for item in history['items']]:
|
||||
raise RuntimeError('Message lost after Redis restart')
|
||||
if api_before != run(NORMAL + ['ps', '-q', 'api']):
|
||||
raise RuntimeError('API restarted during Redis recovery')
|
||||
self.collect_logs(since, 'Redis stop/start and read-after-write')
|
||||
self.burst('after', 'cold', self.args.repetitions+1)
|
||||
|
||||
@contextlib.contextmanager
|
||||
def sample_resources(self, phase):
|
||||
stop = threading.Event()
|
||||
containers = [run(NORMAL + ['ps', '-q', name]) for name in ('api','postgres','redis')]
|
||||
|
||||
def sample():
|
||||
while not stop.is_set():
|
||||
try:
|
||||
output = run(['docker','stats','--no-stream','--format','{{json .}}'] + containers, timeout=10)
|
||||
values = [json.loads(line) for line in output.splitlines() if line.strip()]
|
||||
self.resources.append(dict(phase=phase, timestamp_utc=now(), containers=[
|
||||
{key: value[key] for key in ('Name','CPUPerc','MemUsage','MemPerc','PIDs')} for value in values]))
|
||||
except (RuntimeError, subprocess.TimeoutExpired):
|
||||
self.resources.append(dict(phase=phase, timestamp_utc=now(), error='resource sampling failed'))
|
||||
stop.wait(.2)
|
||||
|
||||
thread = threading.Thread(target=sample, daemon=True)
|
||||
thread.start()
|
||||
try:
|
||||
yield
|
||||
finally:
|
||||
stop.set()
|
||||
thread.join(timeout=12)
|
||||
|
||||
def execute(self):
|
||||
self.use_image(self.args.before_image)
|
||||
extension_created = False
|
||||
try:
|
||||
self.compose('up', '-d', '--no-build', '--force-recreate', 'postgres')
|
||||
self.wait_postgres()
|
||||
if not self.had_extension:
|
||||
self.sql('CREATE EXTENSION pg_stat_statements;')
|
||||
extension_created = True
|
||||
run(NORMAL + ['start', 'redis'])
|
||||
for phase, image in [('before', self.args.before_image), ('after', self.args.after_image)]:
|
||||
self.use_image(image)
|
||||
self.compose('up', '-d', '--no-build', '--no-deps', '--force-recreate', 'api')
|
||||
self.ready()
|
||||
if phase == 'before':
|
||||
self.alice, self.bob, self.eve = [self.actor(label) for label in ('alice', 'bob', 'eve')]
|
||||
self.chat = self.checked('chat_created', 'POST', '/api/v1/chats', self.alice,
|
||||
{'title':'Stampede experiment', 'member_ids':[self.alice['id'],self.bob['id']]}, status=201)
|
||||
self.key = 'chat:' + self.chat['id']
|
||||
self.summary['chat_id'] = self.chat['id']
|
||||
observed = self.checked(phase+'_chat_read_after_create', 'GET', '/api/v1/chats/'+self.chat['id'], self.bob)
|
||||
if observed != self.chat:
|
||||
raise RuntimeError('Chat read-after-create differs')
|
||||
self.summary.setdefault('container_limits', {})[phase] = json.loads(run(['docker','inspect','--format',
|
||||
'{"memory_bytes":{{.HostConfig.Memory}},"nano_cpus":{{.HostConfig.NanoCpus}},"cpu_quota":{{.HostConfig.CpuQuota}}}',
|
||||
run(NORMAL+['ps','-q','api'])]))
|
||||
with self.sample_resources(phase):
|
||||
for repetition in range(1, self.args.repetitions+1):
|
||||
self.burst(phase, 'cold', repetition)
|
||||
for repetition in range(1, 6):
|
||||
self.burst(phase, 'warm', repetition)
|
||||
if not any(r['chat_sql'] > 1 for r in self.runs if r['phase']=='before' and r['mode']=='cold'):
|
||||
raise RuntimeError('Baseline stampede not reproduced')
|
||||
self.functional()
|
||||
self.summary['success'] = True
|
||||
finally:
|
||||
if extension_created:
|
||||
self.sql('DROP EXTENSION pg_stat_statements;')
|
||||
# Restore the original Compose command and fixed normal API image.
|
||||
run(NORMAL + ['up','-d','--no-build','--force-recreate','postgres'])
|
||||
self.wait_postgres()
|
||||
run(NORMAL + ['start','redis'])
|
||||
run(NORMAL + ['up','-d','--no-build','--no-deps','--force-recreate','api'])
|
||||
self.ready()
|
||||
self.summary['restored_preload'] = self.sql('SHOW shared_preload_libraries;')
|
||||
self.summary['extension_restored'] = (self.sql("SELECT count(*) FROM pg_extension WHERE extname='pg_stat_statements';") == ('1' if self.had_extension else '0'))
|
||||
self.logs.append('\n# Final Compose state\n'+run(NORMAL+['ps','-a'])+'\n')
|
||||
self.summary['ended_utc'] = now()
|
||||
self.flush()
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument('--before-image', default='mtusi-messenger:stampede-before')
|
||||
parser.add_argument('--after-image', default='mtusi-messenger:stampede-after')
|
||||
parser.add_argument('--concurrency', type=int, default=32)
|
||||
parser.add_argument('--repetitions', type=int, default=10)
|
||||
parser.add_argument('--lock-ms', type=int, default=200)
|
||||
parser.add_argument('--output', default='evidence/cache-stampede')
|
||||
args = parser.parse_args()
|
||||
if not (2 <= args.concurrency <= 64 and 1 <= args.repetitions <= 50 and 50 <= args.lock_ms <= 500):
|
||||
parser.error('Use concurrency 2..64, repetitions 1..50, lock-ms 50..500')
|
||||
with tempfile.TemporaryDirectory(prefix='cache-stampede-') as directory:
|
||||
Experiment(args, pathlib.Path(directory)/'compose.json').execute()
|
||||
print('Experiment complete; normal Compose restored.', flush=True)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
Executable
+21
@@ -0,0 +1,21 @@
|
||||
#!/bin/sh
|
||||
set -eu
|
||||
|
||||
project_root=$(CDPATH= cd -- "$(dirname -- "$0")/.." && pwd)
|
||||
cd "$project_root"
|
||||
|
||||
if [ ! -d certs ]; then
|
||||
make key-gen
|
||||
fi
|
||||
|
||||
compose() {
|
||||
docker compose --env-file "${COMPOSE_ENV_FILE:-.env}" -f docker-compose.yml "$@"
|
||||
}
|
||||
|
||||
# Validate and build before stopping the API. Recreate containers to apply
|
||||
# current Compose settings, preserve named volumes, and wait for healthchecks.
|
||||
compose config --quiet
|
||||
compose build api
|
||||
compose stop api
|
||||
compose up -d --force-recreate --wait --wait-timeout 120 postgres redis
|
||||
compose up -d --no-build --pull never --force-recreate --wait --wait-timeout 60 api
|
||||
@@ -0,0 +1,109 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"log/slog"
|
||||
"os"
|
||||
"os/signal"
|
||||
"syscall"
|
||||
"time"
|
||||
|
||||
"gitea.privcloud.tech/mtusi2026/internal/adapter/controller/http"
|
||||
"gitea.privcloud.tech/mtusi2026/internal/adapter/repository/cache/outside"
|
||||
"gitea.privcloud.tech/mtusi2026/internal/adapter/repository/storage"
|
||||
"gitea.privcloud.tech/mtusi2026/internal/config"
|
||||
"gitea.privcloud.tech/mtusi2026/internal/pkg/auth/jwtprovider"
|
||||
"gitea.privcloud.tech/mtusi2026/internal/pkg/cache"
|
||||
"gitea.privcloud.tech/mtusi2026/internal/pkg/encrypting"
|
||||
"gitea.privcloud.tech/mtusi2026/internal/pkg/migrator"
|
||||
"gitea.privcloud.tech/mtusi2026/internal/pkg/postgres"
|
||||
"gitea.privcloud.tech/mtusi2026/internal/pkg/postgres/txmanager"
|
||||
"gitea.privcloud.tech/mtusi2026/internal/pkg/rest/middleware"
|
||||
"gitea.privcloud.tech/mtusi2026/internal/pkg/rest/router"
|
||||
"gitea.privcloud.tech/mtusi2026/internal/pkg/validator"
|
||||
"gitea.privcloud.tech/mtusi2026/internal/service/auth"
|
||||
"gitea.privcloud.tech/mtusi2026/internal/service/chat"
|
||||
"gitea.privcloud.tech/mtusi2026/internal/service/user"
|
||||
)
|
||||
|
||||
func main() {
|
||||
time.Local = time.UTC
|
||||
if err := run(); err != nil {
|
||||
slog.Error("application stopped", "error", err)
|
||||
os.Exit(1)
|
||||
}
|
||||
}
|
||||
|
||||
func run() error {
|
||||
cfg, err := config.New()
|
||||
if err != nil {
|
||||
return fmt.Errorf("load server config: %w", err)
|
||||
}
|
||||
|
||||
pgx := postgres.New(cfg.Postgres)
|
||||
rx := cache.New(cfg)
|
||||
postgresMigrator := migrator.New(cfg)
|
||||
tm := txmanager.New(pgx)
|
||||
provider := jwtprovider.New(cfg)
|
||||
encryptor := encrypting.New()
|
||||
|
||||
chatsRepo := storage.NewChatsRepo(pgx)
|
||||
messageRepo := storage.NewMessagesRepo(pgx)
|
||||
refreshTokensRepo := storage.NewRefreshTokensRepo(pgx)
|
||||
userRepo := storage.NewUsersRepo(pgx)
|
||||
|
||||
chatCache := outside.NewChatCache(rx)
|
||||
|
||||
authSvc := auth.New(provider, tm, encryptor, userRepo, refreshTokensRepo)
|
||||
userSvc := user.New(encryptor, userRepo)
|
||||
chatSvc := chat.New(tm, chatsRepo, messageRepo, chatCache)
|
||||
|
||||
httpRouter := router.New(
|
||||
middleware.NewAuthMiddleware(authSvc),
|
||||
middleware.RequestIDMiddleware(),
|
||||
middleware.LoggingMiddleware(),
|
||||
)
|
||||
server := http.New(cfg, httpRouter)
|
||||
requestValidator := validator.NewValidatorImpl()
|
||||
registerRoutes(
|
||||
http.NewAuthHandler(httpRouter, authSvc),
|
||||
http.NewHealthHandler(httpRouter, server),
|
||||
http.NewChatHandler(httpRouter, provider, requestValidator, chatSvc),
|
||||
http.NewUserHandler(httpRouter, provider, requestValidator, userSvc),
|
||||
)
|
||||
|
||||
ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM)
|
||||
defer stop()
|
||||
|
||||
if err = postgresMigrator.Start(ctx); err != nil {
|
||||
return fmt.Errorf("start postgres migrator: %w", err)
|
||||
}
|
||||
if err = server.Start(ctx); err != nil {
|
||||
return fmt.Errorf("start HTTP server: %w", err)
|
||||
}
|
||||
if err = rx.Start(ctx); err != nil {
|
||||
slog.Warn("redis unavailable at startup; continuing without cache", "error", err)
|
||||
}
|
||||
slog.Info("HTTP server started", "address", cfg.Server.BindAddress())
|
||||
|
||||
<-ctx.Done()
|
||||
shutdownCtx, cancel := context.WithTimeout(context.Background(), cfg.Server.ShutdownTimeout)
|
||||
defer cancel()
|
||||
if err = server.Stop(shutdownCtx); err != nil {
|
||||
return fmt.Errorf("stop HTTP server: %w", err)
|
||||
}
|
||||
if err = postgresMigrator.Close(shutdownCtx); err != nil {
|
||||
return fmt.Errorf("close postgres migrator: %w", err)
|
||||
}
|
||||
if err = rx.Close(); err != nil {
|
||||
return fmt.Errorf("close redis: %w", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func registerRoutes(handlers ...http.Handler) {
|
||||
for _, handler := range handlers {
|
||||
handler.RegisterRoutes()
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,386 @@
|
||||
// Command benchmark measures the lab1 HTTP API in fresh, resource-limited containers.
|
||||
package main
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"flag"
|
||||
"fmt"
|
||||
"io"
|
||||
"math"
|
||||
"net/http"
|
||||
"os"
|
||||
"os/exec"
|
||||
"path/filepath"
|
||||
"slices"
|
||||
"strconv"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
)
|
||||
|
||||
const (
|
||||
container = "mtusi-inmemory-benchmark"
|
||||
baseURL = "http://127.0.0.1:18093"
|
||||
)
|
||||
|
||||
type runResult struct {
|
||||
History int `json:"history"`
|
||||
Concurrency int `json:"concurrency"`
|
||||
Repetition int `json:"repetition"`
|
||||
ElapsedSeconds float64 `json:"elapsed_seconds"`
|
||||
ReadSuccess int `json:"read_success"`
|
||||
WriteSuccess int `json:"write_success"`
|
||||
Errors int `json:"errors"`
|
||||
SuccessfulRPS float64 `json:"successful_rps"`
|
||||
LatencyMS map[string]float64 `json:"latency_ms"`
|
||||
RSSBeforeKiB int `json:"rss_kib_before"`
|
||||
RSSPeakKiB int `json:"rss_kib_peak"`
|
||||
}
|
||||
|
||||
type report struct {
|
||||
Image string `json:"image"`
|
||||
Method map[string]any `json:"method"`
|
||||
Runs []runResult `json:"runs"`
|
||||
}
|
||||
|
||||
type workerResult struct {
|
||||
reads int
|
||||
writes int
|
||||
errors int
|
||||
latencies []float64
|
||||
}
|
||||
|
||||
type memoryResult struct {
|
||||
peak int
|
||||
err error
|
||||
}
|
||||
|
||||
func docker(args ...string) (string, error) {
|
||||
command := exec.Command("docker", args...)
|
||||
output, err := command.CombinedOutput()
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("docker %s: %w: %s", strings.Join(args, " "), err, strings.TrimSpace(string(output)))
|
||||
}
|
||||
return strings.TrimSpace(string(output)), nil
|
||||
}
|
||||
|
||||
func rssKiB() (int, error) {
|
||||
status, err := docker("exec", container, "cat", "/proc/1/status")
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
for line := range strings.SplitSeq(status, "\n") {
|
||||
if strings.HasPrefix(line, "VmRSS:") {
|
||||
fields := strings.Fields(line)
|
||||
return strconv.Atoi(fields[1])
|
||||
}
|
||||
}
|
||||
return 0, errors.New("VmRSS is unavailable")
|
||||
}
|
||||
|
||||
func newClient(timeout time.Duration) *http.Client {
|
||||
return &http.Client{
|
||||
Timeout: timeout,
|
||||
Transport: &http.Transport{
|
||||
MaxConnsPerHost: 1,
|
||||
MaxIdleConnsPerHost: 1,
|
||||
IdleConnTimeout: 30 * time.Second,
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
func request(client *http.Client, method, path, user string, body any) (map[string]any, error) {
|
||||
var data io.Reader
|
||||
if body != nil {
|
||||
encoded, err := json.Marshal(body)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
data = bytes.NewReader(encoded)
|
||||
}
|
||||
req, err := http.NewRequest(method, baseURL+path, data)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
req.Header.Set("Accept", "application/json")
|
||||
if user != "" {
|
||||
req.Header.Set("X-User-Id", user)
|
||||
}
|
||||
if body != nil {
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
}
|
||||
response, err := client.Do(req)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer response.Body.Close()
|
||||
content, err := io.ReadAll(io.LimitReader(response.Body, 1<<20))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if response.StatusCode != http.StatusOK && response.StatusCode != http.StatusCreated {
|
||||
return nil, fmt.Errorf("%s %s: HTTP %d: %s", method, path, response.StatusCode, content)
|
||||
}
|
||||
var payload map[string]any
|
||||
if err := json.Unmarshal(content, &payload); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return payload, nil
|
||||
}
|
||||
|
||||
func stringField(payload map[string]any, key string) (string, error) {
|
||||
value, ok := payload[key].(string)
|
||||
if !ok || value == "" {
|
||||
return "", fmt.Errorf("missing %s in API response", key)
|
||||
}
|
||||
return value, nil
|
||||
}
|
||||
|
||||
func percentile(sorted []float64, proportion float64) float64 {
|
||||
if len(sorted) == 0 {
|
||||
return 0
|
||||
}
|
||||
index := int(math.Ceil(float64(len(sorted))*proportion)) - 1
|
||||
if index < 0 {
|
||||
index = 0
|
||||
}
|
||||
return round(sorted[index], 3)
|
||||
}
|
||||
|
||||
func round(value float64, places int) float64 {
|
||||
shift := math.Pow10(places)
|
||||
return math.Round(value*shift) / shift
|
||||
}
|
||||
|
||||
func sampleMemory(stop <-chan struct{}, initial int, result chan<- memoryResult) {
|
||||
ticker := time.NewTicker(250 * time.Millisecond)
|
||||
defer ticker.Stop()
|
||||
peak := initial
|
||||
for {
|
||||
select {
|
||||
case <-stop:
|
||||
result <- memoryResult{peak: peak}
|
||||
return
|
||||
case <-ticker.C:
|
||||
rss, err := rssKiB()
|
||||
if err != nil {
|
||||
result <- memoryResult{err: err}
|
||||
return
|
||||
}
|
||||
peak = max(peak, rss)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func runCase(image string, history, concurrency, repetition int, duration time.Duration) (runResult, error) {
|
||||
row := runResult{History: history, Concurrency: concurrency, Repetition: repetition}
|
||||
if _, err := docker("run", "-d", "--name", container, "--cpus=1", "--memory=512m",
|
||||
"-p", "127.0.0.1:18093:8080", image); err != nil {
|
||||
return row, err
|
||||
}
|
||||
defer func() { _, _ = docker("rm", "-f", container) }()
|
||||
|
||||
setup := newClient(2 * time.Second)
|
||||
defer setup.CloseIdleConnections()
|
||||
readyDeadline := time.Now().Add(20 * time.Second)
|
||||
for {
|
||||
if _, err := request(setup, http.MethodGet, "/health/ready", "", nil); err == nil {
|
||||
break
|
||||
} else if time.Now().After(readyDeadline) {
|
||||
return row, fmt.Errorf("server did not become ready: %w", err)
|
||||
}
|
||||
time.Sleep(100 * time.Millisecond)
|
||||
}
|
||||
userResponse, err := request(setup, http.MethodPost, "/api/v1/users", "", map[string]any{
|
||||
"username": fmt.Sprintf("bench_%d_%d_%d", time.Now().UnixNano(), history, repetition),
|
||||
"display_name": "Benchmark",
|
||||
})
|
||||
if err != nil {
|
||||
return row, err
|
||||
}
|
||||
user, err := stringField(userResponse, "id")
|
||||
if err != nil {
|
||||
return row, err
|
||||
}
|
||||
chatResponse, err := request(setup, http.MethodPost, "/api/v1/chats", user, map[string]any{
|
||||
"title": "Benchmark", "member_ids": []string{user},
|
||||
})
|
||||
if err != nil {
|
||||
return row, err
|
||||
}
|
||||
chat, err := stringField(chatResponse, "id")
|
||||
if err != nil {
|
||||
return row, err
|
||||
}
|
||||
path := "/api/v1/chats/" + chat + "/messages"
|
||||
for index := range history {
|
||||
if _, err := request(setup, http.MethodPost, path, user, map[string]string{
|
||||
"text": fmt.Sprintf("seed-%d", index),
|
||||
}); err != nil {
|
||||
return row, fmt.Errorf("seed message %d: %w", index, err)
|
||||
}
|
||||
}
|
||||
row.RSSBeforeKiB, err = rssKiB()
|
||||
if err != nil {
|
||||
return row, err
|
||||
}
|
||||
|
||||
start := make(chan struct{})
|
||||
results := make(chan workerResult, concurrency)
|
||||
stopSampling := make(chan struct{})
|
||||
memory := make(chan memoryResult, 1)
|
||||
go sampleMemory(stopSampling, row.RSSBeforeKiB, memory)
|
||||
var group sync.WaitGroup
|
||||
group.Add(concurrency)
|
||||
deadline := time.Now().Add(duration)
|
||||
started := time.Now()
|
||||
for workerID := range concurrency {
|
||||
go func() {
|
||||
defer group.Done()
|
||||
local := newClient(5 * time.Second)
|
||||
defer local.CloseIdleConnections()
|
||||
result := workerResult{}
|
||||
<-start
|
||||
for index := 0; time.Now().Before(deadline); index++ {
|
||||
began := time.Now()
|
||||
var err error
|
||||
if index%10 == 0 {
|
||||
_, err = request(local, http.MethodPost, path, user, map[string]string{
|
||||
"text": fmt.Sprintf("load-%d-%d-%d", repetition, workerID, index),
|
||||
})
|
||||
if err == nil {
|
||||
result.writes++
|
||||
}
|
||||
} else {
|
||||
var page map[string]any
|
||||
page, err = request(local, http.MethodGet, path+"?limit=50", user, nil)
|
||||
if err == nil {
|
||||
items, ok := page["items"].([]any)
|
||||
if !ok || len(items) != 50 {
|
||||
err = errors.New("short first page")
|
||||
} else {
|
||||
result.reads++
|
||||
}
|
||||
}
|
||||
}
|
||||
if err != nil {
|
||||
result.errors++
|
||||
} else {
|
||||
result.latencies = append(result.latencies, float64(time.Since(began).Microseconds())/1000)
|
||||
}
|
||||
}
|
||||
results <- result
|
||||
}()
|
||||
}
|
||||
close(start)
|
||||
group.Wait()
|
||||
row.ElapsedSeconds = round(time.Since(started).Seconds(), 3)
|
||||
close(stopSampling)
|
||||
memorySample := <-memory
|
||||
if memorySample.err != nil {
|
||||
return row, memorySample.err
|
||||
}
|
||||
row.RSSPeakKiB = memorySample.peak
|
||||
if finalRSS, err := rssKiB(); err == nil {
|
||||
row.RSSPeakKiB = max(row.RSSPeakKiB, finalRSS)
|
||||
} else {
|
||||
return row, err
|
||||
}
|
||||
latencies := make([]float64, 0)
|
||||
for range concurrency {
|
||||
result := <-results
|
||||
row.ReadSuccess += result.reads
|
||||
row.WriteSuccess += result.writes
|
||||
row.Errors += result.errors
|
||||
latencies = append(latencies, result.latencies...)
|
||||
}
|
||||
if len(latencies) == 0 {
|
||||
return row, errors.New("no successful requests")
|
||||
}
|
||||
slices.Sort(latencies)
|
||||
row.SuccessfulRPS = round(float64(len(latencies))/row.ElapsedSeconds, 2)
|
||||
row.LatencyMS = map[string]float64{
|
||||
"p95": percentile(latencies, 0.95),
|
||||
"p99": percentile(latencies, 0.99),
|
||||
}
|
||||
return row, nil
|
||||
}
|
||||
|
||||
func parseValues(raw string, minimum int) ([]int, error) {
|
||||
values := make([]int, 0)
|
||||
for part := range strings.SplitSeq(raw, ",") {
|
||||
value, err := strconv.Atoi(strings.TrimSpace(part))
|
||||
if err != nil || value < minimum {
|
||||
return nil, fmt.Errorf("invalid value %q", part)
|
||||
}
|
||||
values = append(values, value)
|
||||
}
|
||||
return values, nil
|
||||
}
|
||||
|
||||
func save(path string, data report) error {
|
||||
encoded, err := json.MarshalIndent(data, "", " ")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if err := os.MkdirAll(filepath.Dir(path), 0o755); err != nil {
|
||||
return err
|
||||
}
|
||||
return os.WriteFile(path, append(encoded, '\n'), 0o644)
|
||||
}
|
||||
|
||||
func main() {
|
||||
image := flag.String("image", "", "Docker image to benchmark")
|
||||
output := flag.String("output", "", "JSON output path")
|
||||
historiesArg := flag.String("histories", "100,500,1500", "Comma-separated history sizes")
|
||||
concurrenciesArg := flag.String("concurrencies", "1,4,10", "Comma-separated client counts")
|
||||
repeats := flag.Int("repeats", 3, "Runs per combination")
|
||||
duration := flag.Duration("duration", 5*time.Second, "Measured duration per run")
|
||||
flag.Parse()
|
||||
if *image == "" || *output == "" || *repeats < 1 || *duration <= 0 {
|
||||
fmt.Fprintln(os.Stderr, "image, output, positive repeats and duration are required")
|
||||
os.Exit(2)
|
||||
}
|
||||
histories, err := parseValues(*historiesArg, 50)
|
||||
if err != nil {
|
||||
fmt.Fprintln(os.Stderr, err)
|
||||
os.Exit(2)
|
||||
}
|
||||
concurrencies, err := parseValues(*concurrenciesArg, 1)
|
||||
if err != nil {
|
||||
fmt.Fprintln(os.Stderr, err)
|
||||
os.Exit(2)
|
||||
}
|
||||
data := report{
|
||||
Image: *image,
|
||||
Method: map[string]any{
|
||||
"histories": histories, "concurrencies": concurrencies,
|
||||
"repeats": *repeats, "duration_seconds": duration.Seconds(),
|
||||
"mix": "90% first-page GET, 10% POST per client; persistent HTTP connections",
|
||||
"limits": "1 CPU, 512 MiB; fresh container and history per case",
|
||||
"rss": "VmRSS from /proc/1/status every 250 ms (sampled peak)",
|
||||
"latency": "successful requests only; errors counted separately; closed-loop workload",
|
||||
},
|
||||
Runs: make([]runResult, 0, len(histories)*len(concurrencies)*(*repeats)),
|
||||
}
|
||||
for _, history := range histories {
|
||||
for _, concurrency := range concurrencies {
|
||||
for repetition := 1; repetition <= *repeats; repetition++ {
|
||||
row, err := runCase(*image, history, concurrency, repetition, *duration)
|
||||
if err != nil {
|
||||
fmt.Fprintln(os.Stderr, err)
|
||||
os.Exit(1)
|
||||
}
|
||||
data.Runs = append(data.Runs, row)
|
||||
if err := save(*output, data); err != nil {
|
||||
fmt.Fprintln(os.Stderr, err)
|
||||
os.Exit(1)
|
||||
}
|
||||
encoded, _ := json.Marshal(row)
|
||||
fmt.Println(string(encoded))
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,57 @@
|
||||
module gitea.privcloud.tech/mtusi2026
|
||||
|
||||
go 1.27.0
|
||||
|
||||
require (
|
||||
github.com/go-chi/chi/v5 v5.5.0
|
||||
github.com/go-playground/validator/v10 v10.30.5
|
||||
github.com/golang-jwt/jwt/v5 v5.3.1
|
||||
github.com/google/uuid v1.6.0
|
||||
github.com/jackc/pgerrcode v0.0.0-20250907135507-afb5586c32a6
|
||||
github.com/jackc/pgx/v5 v5.11.0
|
||||
github.com/oapi-codegen/runtime v1.4.2
|
||||
github.com/redis/go-redis/v9 v9.23.0
|
||||
github.com/spf13/viper v1.21.0
|
||||
go.uber.org/multierr v1.11.0
|
||||
golang.org/x/crypto v0.57.0
|
||||
golang.org/x/sync v0.23.0
|
||||
google.golang.org/grpc v1.85.0
|
||||
)
|
||||
|
||||
require (
|
||||
dario.cat/mergo v1.0.2 // indirect
|
||||
github.com/Masterminds/goutils v1.1.1 // indirect
|
||||
github.com/Masterminds/semver/v3 v3.5.0 // indirect
|
||||
github.com/Masterminds/sprig/v3 v3.3.0 // indirect
|
||||
github.com/Masterminds/squirrel v1.5.4 // indirect
|
||||
github.com/cespare/xxhash/v2 v2.3.0 // indirect
|
||||
github.com/fsnotify/fsnotify v1.9.0 // indirect
|
||||
github.com/gabriel-vasile/mimetype v1.4.15 // indirect
|
||||
github.com/go-playground/locales v0.14.1 // indirect
|
||||
github.com/go-playground/universal-translator v0.18.1 // indirect
|
||||
github.com/go-viper/mapstructure/v2 v2.4.0 // indirect
|
||||
github.com/huandu/xstrings v1.5.0 // 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/jackc/tern/v2 v2.4.3 // indirect
|
||||
github.com/lann/builder v0.0.0-20180802200727-47ae307949d0 // indirect
|
||||
github.com/lann/ps v0.0.0-20150810152359-62de8c46ede0 // indirect
|
||||
github.com/leodido/go-urn v1.5.0 // indirect
|
||||
github.com/mcosta74/pgx-slog v0.4.1 // indirect
|
||||
github.com/mitchellh/copystructure v1.2.0 // indirect
|
||||
github.com/mitchellh/reflectwalk v1.0.2 // indirect
|
||||
github.com/pelletier/go-toml/v2 v2.4.3-0.20260624044523-35f78d5908f1 // indirect
|
||||
github.com/sagikazarmark/locafero v0.11.0 // indirect
|
||||
github.com/shopspring/decimal v1.4.0 // indirect
|
||||
github.com/sourcegraph/conc v0.3.1-0.20240121214520-5f936abd7ae8 // indirect
|
||||
github.com/spf13/afero v1.15.0 // indirect
|
||||
github.com/spf13/cast v1.10.0 // indirect
|
||||
github.com/spf13/pflag v1.0.10 // indirect
|
||||
github.com/subosito/gotenv v1.6.0 // indirect
|
||||
github.com/vgarvardt/pgx-google-uuid/v5 v5.6.0 // indirect
|
||||
go.uber.org/atomic v1.12.0 // indirect
|
||||
go.yaml.in/yaml/v3 v3.0.5 // indirect
|
||||
golang.org/x/sys v0.48.0 // indirect
|
||||
golang.org/x/text v0.42.0 // indirect
|
||||
)
|
||||
+131
@@ -0,0 +1,131 @@
|
||||
dario.cat/mergo v1.0.2 h1:85+piFYR1tMbRrLcDwR18y4UKJ3aH1Tbzi24VRW1TK8=
|
||||
dario.cat/mergo v1.0.2/go.mod h1:E/hbnu0NxMFBjpMIE34DRGLWqDy0g5FuKDhCb31ngxA=
|
||||
github.com/Masterminds/goutils v1.1.1 h1:5nUrii3FMTL5diU80unEVvNevw1nH4+ZV4DSLVJLSYI=
|
||||
github.com/Masterminds/goutils v1.1.1/go.mod h1:8cTjp+g8YejhMuvIA5y2vz3BpJxksy863GQaJW2MFNU=
|
||||
github.com/Masterminds/semver/v3 v3.5.0 h1:kQceYJfbupGfZOKZQg0kou0DgAKhzDg2NZPAwZ/2OOE=
|
||||
github.com/Masterminds/semver/v3 v3.5.0/go.mod h1:4V+yj/TJE1HU9XfppCwVMZq3I84lprf4nC11bSS5beM=
|
||||
github.com/Masterminds/sprig/v3 v3.3.0 h1:mQh0Yrg1XPo6vjYXgtf5OtijNAKJRNcTdOOGZe3tPhs=
|
||||
github.com/Masterminds/sprig/v3 v3.3.0/go.mod h1:Zy1iXRYNqNLUolqCpL4uhk6SHUMAOSCzdgBfDb35Lz0=
|
||||
github.com/Masterminds/squirrel v1.5.4 h1:uUcX/aBc8O7Fg9kaISIUsHXdKuqehiXAMQTYX8afzqM=
|
||||
github.com/Masterminds/squirrel v1.5.4/go.mod h1:NNaOrjSoIDfDA40n7sr2tPNZRfjzjA400rg+riTZj10=
|
||||
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/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
|
||||
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
|
||||
github.com/frankban/quicktest v1.14.6 h1:7Xjx+VpznH+oBnejlPUj8oUpdxnVs4f8XU8WnHkI4W8=
|
||||
github.com/frankban/quicktest v1.14.6/go.mod h1:4ptaffx2x8+WTWXmUCuVU6aPUX1/Mz7zb5vbUoiM6w0=
|
||||
github.com/fsnotify/fsnotify v1.9.0 h1:2Ml+OJNzbYCTzsxtv8vKSFD9PbJjmhYF14k/jKC7S9k=
|
||||
github.com/fsnotify/fsnotify v1.9.0/go.mod h1:8jBTzvmWwFyi3Pb8djgCCO5IBqzKJ/Jwo8TRcHyHii0=
|
||||
github.com/gabriel-vasile/mimetype v1.4.15 h1:05iP/CYtZ/w455R/KZM6rZ5ieAdh99UPtd+d3YzLmaI=
|
||||
github.com/gabriel-vasile/mimetype v1.4.15/go.mod h1:azpTcoLcDZRNgFou5j+APrqQx9HqVPWa6ijYQIIVswQ=
|
||||
github.com/go-chi/chi/v5 v5.5.0 h1:xdKQ1dJmVJsmgahrXSKhUx8NyVPzpwdlyrrQFpMPJgg=
|
||||
github.com/go-chi/chi/v5 v5.5.0/go.mod h1:d1IG7GtKPSjPyBP365PH8sAGVHk3qfB/IhjFNRH1wWM=
|
||||
github.com/go-playground/assert/v2 v2.2.0 h1:JvknZsQTYeFEAhQwI4qEt9cyV5ONwRHC+lYKSsYSR8s=
|
||||
github.com/go-playground/assert/v2 v2.2.0/go.mod h1:VDjEfimB/XKnb+ZQfWdccd7VUvScMdVu0Titje2rxJ4=
|
||||
github.com/go-playground/locales v0.14.1 h1:EWaQ/wswjilfKLTECiXz7Rh+3BjFhfDFKv/oXslEjJA=
|
||||
github.com/go-playground/locales v0.14.1/go.mod h1:hxrqLVvrK65+Rwrd5Fc6F2O76J/NuW9t0sjnWqG1slY=
|
||||
github.com/go-playground/universal-translator v0.18.1 h1:Bcnm0ZwsGyWbCzImXv+pAJnYK9S473LQFuzCbDbfSFY=
|
||||
github.com/go-playground/universal-translator v0.18.1/go.mod h1:xekY+UJKNuX9WP91TpwSH2VMlDf28Uj24BCp08ZFTUY=
|
||||
github.com/go-playground/validator/v10 v10.30.5 h1:YyCXvVShZbs2Sm3Mb53eNOlhRXctSOzW5QJAouCTZL4=
|
||||
github.com/go-playground/validator/v10 v10.30.5/go.mod h1:wEqiaov48pXX1kjhc3Da8y0M0Dtg/BK7gurFBLgwFrQ=
|
||||
github.com/go-viper/mapstructure/v2 v2.4.0 h1:EBsztssimR/CONLSZZ04E8qAkxNYq4Qp9LvH92wZUgs=
|
||||
github.com/go-viper/mapstructure/v2 v2.4.0/go.mod h1:oJDH3BJKyqBA2TXFhDsKDGDTlndYOZ6rGS0BRZIxGhM=
|
||||
github.com/golang-jwt/jwt/v5 v5.3.1 h1:kYf81DTWFe7t+1VvL7eS+jKFVWaUnK9cB1qbwn63YCY=
|
||||
github.com/golang-jwt/jwt/v5 v5.3.1/go.mod h1:fxCRLWMO43lRc8nhHWY6LGqRcf+1gQWArsqaEUEa5bE=
|
||||
github.com/google/go-cmp v0.6.0 h1:ofyhxvXcZhMsU5ulbFiLKl/XBFqE1GSq7atu8tAmTRI=
|
||||
github.com/google/go-cmp v0.6.0/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY=
|
||||
github.com/google/go-cmp v0.7.0 h1:wk8382ETsv4JYUZwIsn6YpYiWiBsYLSJiTsyBybVuN8=
|
||||
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/huandu/xstrings v1.5.0 h1:2ag3IFq9ZDANvthTwTiqSSZLjDc+BedvHPAp5tJy2TI=
|
||||
github.com/huandu/xstrings v1.5.0/go.mod h1:y5/lhBue+AyNmUVz9RLU9xbLR0o4KIIExikq4ovT0aE=
|
||||
github.com/jackc/pgerrcode v0.0.0-20250907135507-afb5586c32a6 h1:D/V0gu4zQ3cL2WKeVNVM4r2gLxGGf6McLwgXzRTo2RQ=
|
||||
github.com/jackc/pgerrcode v0.0.0-20250907135507-afb5586c32a6/go.mod h1:a/s9Lp5W7n/DD0VrVoyJ00FbP2ytTPDVOivvn2bMlds=
|
||||
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.11.0 h1:IzBBtyK9AHqf98cctWFifYSci2hgQR/cd56wB4p+ogg=
|
||||
github.com/jackc/pgx/v5 v5.11.0/go.mod h1:mal1tBGAFfLHvZzaYh77YS/eC6IX9OWbRV1QIIM0Jn4=
|
||||
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/jackc/tern/v2 v2.4.3 h1:g293d3OZgW7OFEhsYXgEv0C21jea2boNr0VR4K5I7OY=
|
||||
github.com/jackc/tern/v2 v2.4.3/go.mod h1:rMpMuRYcff5wWLptoTSO1qcDxJ4OodysvK17i2SVBys=
|
||||
github.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE=
|
||||
github.com/kr/pretty v0.3.1/go.mod h1:hoEshYVHaxMs3cyo3Yncou5ZscifuDolrwPKZanG3xk=
|
||||
github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY=
|
||||
github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE=
|
||||
github.com/lann/builder v0.0.0-20180802200727-47ae307949d0 h1:SOEGU9fKiNWd/HOJuq6+3iTQz8KNCLtVX6idSoTLdUw=
|
||||
github.com/lann/builder v0.0.0-20180802200727-47ae307949d0/go.mod h1:dXGbAdH5GtBTC4WfIxhKZfyBF/HBFgRZSWwZ9g/He9o=
|
||||
github.com/lann/ps v0.0.0-20150810152359-62de8c46ede0 h1:P6pPBnrTSX3DEVR4fDembhRWSsG5rVo6hYhAB/ADZrk=
|
||||
github.com/lann/ps v0.0.0-20150810152359-62de8c46ede0/go.mod h1:vmVJ0l/dxyfGW6FmdpVm2joNMFikkuWg0EoCKLGUMNw=
|
||||
github.com/leodido/go-urn v1.5.0 h1:pLqT2kq1zpHW/1D18QMjMpdtX7cekxqtJJjg5ANyWw0=
|
||||
github.com/leodido/go-urn v1.5.0/go.mod h1:9BORnCDhdPBJNDEX+w1bJisa8yOKYi116VeO96s4ifE=
|
||||
github.com/mcosta74/pgx-slog v0.4.1 h1:Rt25l/jE5tu1ioqPDrqY17Kv6REdsM0L9WCT+hFw1rw=
|
||||
github.com/mcosta74/pgx-slog v0.4.1/go.mod h1:BCpubkiENkWQ8MvZ4a9LJgWuBzC5UpWoJmQ1/SOlv+M=
|
||||
github.com/mitchellh/copystructure v1.2.0 h1:vpKXTN4ewci03Vljg/q9QvCGUDttBOGBIa15WveJJGw=
|
||||
github.com/mitchellh/copystructure v1.2.0/go.mod h1:qLl+cE2AmVv+CoeAwDPye/v+N2HKCj9FbZEVFJRxO9s=
|
||||
github.com/mitchellh/reflectwalk v1.0.2 h1:G2LzWKi524PWgd3mLHV8Y5k7s6XUvT0Gef6zxSIeXaQ=
|
||||
github.com/mitchellh/reflectwalk v1.0.2/go.mod h1:mSTlrgnPZtwu0c4WaC2kGObEpuNDbx0jmZXqmk4esnw=
|
||||
github.com/oapi-codegen/runtime v1.4.2 h1:GMxFVYLzoYLua+/KvzgSphkyK1lLTReQI9Vf4hvATKE=
|
||||
github.com/oapi-codegen/runtime v1.4.2/go.mod h1:GwV7hC2hviaMzj+ITfHVRESK5J2W/GefVwIND/bMGvU=
|
||||
github.com/pelletier/go-toml/v2 v2.2.4 h1:mye9XuhQ6gvn5h28+VilKrrPoQVanw5PMw/TB0t5Ec4=
|
||||
github.com/pelletier/go-toml/v2 v2.2.4/go.mod h1:2gIqNv+qfxSVS7cM2xJQKtLSTLUE9V8t9Stt+h56mCY=
|
||||
github.com/pelletier/go-toml/v2 v2.4.3-0.20260624044523-35f78d5908f1 h1:gIZQQ2+wbsdQGWLPDSdJFptR25tBCjSC0KbSIQZ1rgE=
|
||||
github.com/pelletier/go-toml/v2 v2.4.3-0.20260624044523-35f78d5908f1/go.mod h1:2gIqNv+qfxSVS7cM2xJQKtLSTLUE9V8t9Stt+h56mCY=
|
||||
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
|
||||
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
|
||||
github.com/redis/go-redis/v9 v9.23.0 h1:/TTVdJa8BRNsybwwGGnmiYktHNlUXtbOQxlWpHBPL3s=
|
||||
github.com/redis/go-redis/v9 v9.23.0/go.mod h1:EWP2UUk+XDaI1s5nQB5mablZN6vccXlmBQTyfnF87D0=
|
||||
github.com/rogpeppe/go-internal v1.9.0 h1:73kH8U+JUqXU8lRuOHeVHaa/SZPifC7BkcraZVejAe8=
|
||||
github.com/rogpeppe/go-internal v1.9.0/go.mod h1:WtVeX8xhTBvf0smdhujwtBcq4Qrzq/fJaraNFVN+nFs=
|
||||
github.com/sagikazarmark/locafero v0.11.0 h1:1iurJgmM9G3PA/I+wWYIOw/5SyBtxapeHDcg+AAIFXc=
|
||||
github.com/sagikazarmark/locafero v0.11.0/go.mod h1:nVIGvgyzw595SUSUE6tvCp3YYTeHs15MvlmU87WwIik=
|
||||
github.com/shopspring/decimal v1.4.0 h1:bxl37RwXBklmTi0C79JfXCEBD1cqqHt0bbgBAGFp81k=
|
||||
github.com/shopspring/decimal v1.4.0/go.mod h1:gawqmDU56v4yIKSwfBSFip1HdCCXN8/+DMd9qYNcwME=
|
||||
github.com/sourcegraph/conc v0.3.1-0.20240121214520-5f936abd7ae8 h1:+jumHNA0Wrelhe64i8F6HNlS8pkoyMv5sreGx2Ry5Rw=
|
||||
github.com/sourcegraph/conc v0.3.1-0.20240121214520-5f936abd7ae8/go.mod h1:3n1Cwaq1E1/1lhQhtRK2ts/ZwZEhjcQeJQ1RuC6Q/8U=
|
||||
github.com/spf13/afero v1.15.0 h1:b/YBCLWAJdFWJTN9cLhiXXcD7mzKn9Dm86dNnfyQw1I=
|
||||
github.com/spf13/afero v1.15.0/go.mod h1:NC2ByUVxtQs4b3sIUphxK0NioZnmxgyCrfzeuq8lxMg=
|
||||
github.com/spf13/cast v1.10.0 h1:h2x0u2shc1QuLHfxi+cTJvs30+ZAHOGRic8uyGTDWxY=
|
||||
github.com/spf13/cast v1.10.0/go.mod h1:jNfB8QC9IA6ZuY2ZjDp0KtFO2LZZlg4S/7bzP6qqeHo=
|
||||
github.com/spf13/pflag v1.0.10 h1:4EBh2KAYBwaONj6b2Ye1GiHfwjqyROoF4RwYO+vPwFk=
|
||||
github.com/spf13/pflag v1.0.10/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An2Bg=
|
||||
github.com/spf13/viper v1.21.0 h1:x5S+0EU27Lbphp4UKm1C+1oQO+rKx36vfCoaVebLFSU=
|
||||
github.com/spf13/viper v1.21.0/go.mod h1:P0lhsswPGWD/1lZJ9ny3fYnVqxiegrlNrEmgLjbTCAY=
|
||||
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
|
||||
github.com/stretchr/testify v1.2.2/go.mod h1:a8OnRcib4nhh0OaRAV+Yts87kKdq0PP7pXfy6kDkUVs=
|
||||
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.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U=
|
||||
github.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U=
|
||||
github.com/subosito/gotenv v1.6.0 h1:9NlTDc1FTs4qu0DDq7AEtTPNw6SVm7uBMsUCUjABIf8=
|
||||
github.com/subosito/gotenv v1.6.0/go.mod h1:Dk4QP5c2W3ibzajGcXpNraDfq2IrhjMIvMSWPKKo0FU=
|
||||
github.com/vgarvardt/pgx-google-uuid/v5 v5.6.0 h1:EhPtK0mgrgaTMXpegE69hvoSOVC1Ahk8+QJ9B8b+OdU=
|
||||
github.com/vgarvardt/pgx-google-uuid/v5 v5.6.0/go.mod h1:5LtFrNEkgzxHvXPO9eOvcXsSn9/KeKYgx9kjeI2oXQI=
|
||||
go.uber.org/atomic v1.12.0 h1:BvcXdFKuviU4fTL/f+SxdQ5qJX/Jix8pAkgdUcb3XOE=
|
||||
go.uber.org/atomic v1.12.0/go.mod h1:I6c4cg+6HCxRjfjSsYtApoFILnpc0CGUdGkXVqbYVNk=
|
||||
go.uber.org/multierr v1.11.0 h1:blXXJkSxSSfBVBlC76pxqeO+LN3aDfLQo+309xJstO0=
|
||||
go.uber.org/multierr v1.11.0/go.mod h1:20+QtiLqy0Nd6FdQB9TLXag12DsQkrbs3htMFfDN80Y=
|
||||
go.yaml.in/yaml/v3 v3.0.4 h1:tfq32ie2Jv2UxXFdLJdh3jXuOzWiL1fo0bu/FbuKpbc=
|
||||
go.yaml.in/yaml/v3 v3.0.4/go.mod h1:DhzuOOF2ATzADvBadXxruRBLzYTpT36CKvDb3+aBEFg=
|
||||
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.57.0 h1:3ZVCjf8Ggz7zneR/EHRVx68Ctf+2pmIMP2UFhh9cC6M=
|
||||
golang.org/x/crypto v0.57.0/go.mod h1:Fdz0i5U6CoizGwLda9DttjSk6qlZo25zYNtR+ycvuZA=
|
||||
golang.org/x/sync v0.23.0 h1:KameEIfc1IkluZyXWLn39Wd4tURc6GbCiISGiZm2bQk=
|
||||
golang.org/x/sync v0.23.0/go.mod h1:sUUOizhqBxiL6pEWpqNLUiaJn1ShEbZ6BBqskPbjZm0=
|
||||
golang.org/x/sys v0.48.0 h1:bbX/i/6MgT9BVLM9RT1thmxL04yeTAhbEz4SyadbXoo=
|
||||
golang.org/x/sys v0.48.0/go.mod h1:hNLxWAXmnKAxqDtdwIYC4bM9oQPEecfsnNMuSxOs3og=
|
||||
golang.org/x/text v0.42.0 h1:JbOZXgfeCPU9gacVtYliJqOhD+zhrEqK4LfdpmlUZqI=
|
||||
golang.org/x/text v0.42.0/go.mod h1:ojzP1Z+2QtioaF8DTtO8K5q7JWVVYwZKenzujK0Zd0E=
|
||||
google.golang.org/grpc v1.85.0 h1:BPBCfuVRQ1qvBhKDOq9uvQllMvO59rKsYhXpp7Dd8vw=
|
||||
google.golang.org/grpc v1.85.0/go.mod h1:0rQrOD58yjal/0EaVbGBANindixsCZNQPDV3VKtaKuQ=
|
||||
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
|
||||
gopkg.in/check.v1 v1.0.0-20190902080502-41f04d3bba15 h1:YR8cESwS4TdDjEe65xsg0ogRM/Nc3DYOhEAlW+xobZo=
|
||||
gopkg.in/check.v1 v1.0.0-20190902080502-41f04d3bba15/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
|
||||
gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk=
|
||||
gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
|
||||
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
|
||||
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
|
||||
@@ -0,0 +1,88 @@
|
||||
package http
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
|
||||
"gitea.privcloud.tech/mtusi2026/internal/dto"
|
||||
"gitea.privcloud.tech/mtusi2026/internal/gen/contracts"
|
||||
"gitea.privcloud.tech/mtusi2026/internal/pkg/apperr"
|
||||
"gitea.privcloud.tech/mtusi2026/internal/pkg/rest/framework"
|
||||
"gitea.privcloud.tech/mtusi2026/internal/pkg/rest/router"
|
||||
"gitea.privcloud.tech/mtusi2026/internal/service/auth"
|
||||
)
|
||||
|
||||
type AuthHandler struct {
|
||||
router router.Router
|
||||
|
||||
auth auth.API
|
||||
}
|
||||
|
||||
func NewAuthHandler(r router.Router, api auth.API) Handler {
|
||||
return &AuthHandler{
|
||||
router: r,
|
||||
auth: api,
|
||||
}
|
||||
}
|
||||
|
||||
func (h *AuthHandler) RegisterRoutes() {
|
||||
h.router.Public(http.MethodPost, "/api/v1/auth/sessions", h.Login)
|
||||
h.router.Private(http.MethodDelete, "/api/v1/auth/sessions/current", h.Logout)
|
||||
}
|
||||
|
||||
func (h *AuthHandler) Login(w http.ResponseWriter, r *http.Request) {
|
||||
ctx := r.Context()
|
||||
|
||||
username, password, ok := r.BasicAuth()
|
||||
if !ok || username == "" || password == "" {
|
||||
w.Header().Set(
|
||||
"WWW-Authenticate",
|
||||
`Basic realm="messenger", charset="UTF-8"`,
|
||||
)
|
||||
framework.JSONError(ctx, w, apperr.New(apperr.CodeUnauthorized, "invalid credentials"))
|
||||
return
|
||||
}
|
||||
|
||||
resp, err := h.auth.Login(ctx, dto.Login{
|
||||
Username: username,
|
||||
Password: password,
|
||||
})
|
||||
if err != nil {
|
||||
if apperr.HTTPStatusFromError(err) == http.StatusUnauthorized {
|
||||
w.Header().Set("WWW-Authenticate", `Basic realm="messenger", charset="UTF-8"`)
|
||||
}
|
||||
framework.JSONError(ctx, w, err)
|
||||
return
|
||||
}
|
||||
|
||||
framework.JSONResponse(w, http.StatusCreated, contracts.Session{
|
||||
ExpiresAt: resp.ExpiresAt,
|
||||
Token: resp.Tokens.RefreshToken.Payload,
|
||||
TokenType: resp.TokenType,
|
||||
User: contracts.User{
|
||||
CreatedAt: resp.User.CreatedAt,
|
||||
DisplayName: resp.User.DisplayName,
|
||||
Id: resp.User.ID,
|
||||
Username: resp.User.Username,
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
func (h *AuthHandler) Logout(w http.ResponseWriter, r *http.Request) {
|
||||
ctx := r.Context()
|
||||
|
||||
token, exists := framework.Token(r)
|
||||
if !exists {
|
||||
framework.JSONError(ctx, w, apperr.New(apperr.CodeUnauthorized, "missing token in header"))
|
||||
return
|
||||
}
|
||||
|
||||
err := h.auth.Logout(ctx, dto.RefreshToken{
|
||||
Payload: token,
|
||||
})
|
||||
if err != nil {
|
||||
framework.JSONError(ctx, w, err)
|
||||
return
|
||||
}
|
||||
|
||||
framework.JSONResponse(w, http.StatusNoContent, nil)
|
||||
}
|
||||
@@ -0,0 +1,261 @@
|
||||
package http
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"strings"
|
||||
"unicode/utf8"
|
||||
|
||||
"github.com/google/uuid"
|
||||
|
||||
"gitea.privcloud.tech/mtusi2026/internal/dto"
|
||||
"gitea.privcloud.tech/mtusi2026/internal/gen/contracts"
|
||||
"gitea.privcloud.tech/mtusi2026/internal/pkg/apperr"
|
||||
"gitea.privcloud.tech/mtusi2026/internal/pkg/auth/jwtprovider"
|
||||
"gitea.privcloud.tech/mtusi2026/internal/pkg/rest/framework"
|
||||
"gitea.privcloud.tech/mtusi2026/internal/pkg/rest/router"
|
||||
"gitea.privcloud.tech/mtusi2026/internal/pkg/validator"
|
||||
"gitea.privcloud.tech/mtusi2026/internal/service/chat"
|
||||
)
|
||||
|
||||
type ChatHandler struct {
|
||||
router router.Router
|
||||
provider jwtprovider.Provider
|
||||
validator *validator.ValidatorImpl
|
||||
|
||||
chat chat.API
|
||||
}
|
||||
|
||||
func NewChatHandler(r router.Router, provider jwtprovider.Provider, v *validator.ValidatorImpl, api chat.API) Handler {
|
||||
return &ChatHandler{
|
||||
router: r,
|
||||
provider: provider,
|
||||
validator: v,
|
||||
chat: api,
|
||||
}
|
||||
}
|
||||
|
||||
func (h *ChatHandler) RegisterRoutes() {
|
||||
h.router.Private(http.MethodPost, "/api/v1/chats", h.Create)
|
||||
h.router.Private(http.MethodGet, "/api/v1/chats", h.Get)
|
||||
h.router.Private(http.MethodGet, "/api/v1/chats/{chat_id}", h.GetByID)
|
||||
h.router.Private(http.MethodPost, "/api/v1/chats/{chat_id}/messages", h.SendMessage)
|
||||
h.router.Private(http.MethodGet, "/api/v1/chats/{chat_id}/messages", h.GetMessages)
|
||||
}
|
||||
|
||||
func (h *ChatHandler) Create(w http.ResponseWriter, r *http.Request) {
|
||||
ctx := r.Context()
|
||||
|
||||
userData, err := framework.ParseToken(r, h.provider)
|
||||
if err != nil {
|
||||
framework.JSONError(ctx, w, err)
|
||||
return
|
||||
}
|
||||
|
||||
var req contracts.CreateChat
|
||||
if !framework.Decode(w, r, &req) || !framework.Validate(w, r, h.validator, &req) {
|
||||
return
|
||||
}
|
||||
|
||||
if userData.UserID == uuid.Nil ||
|
||||
!validText(req.Title, 100) ||
|
||||
len(req.MemberIds) < 1 ||
|
||||
len(req.MemberIds) > 100 {
|
||||
framework.JSONError(ctx, w, apperr.New(apperr.CodeBadRequest, "invalid chat fields"))
|
||||
return
|
||||
}
|
||||
|
||||
resp, err := h.chat.CreateChat(ctx, dto.CreateChat{
|
||||
CreatorID: userData.UserID,
|
||||
Title: req.Title,
|
||||
MemberIDs: req.MemberIds,
|
||||
})
|
||||
if err != nil {
|
||||
framework.JSONError(ctx, w, err)
|
||||
return
|
||||
}
|
||||
|
||||
framework.JSONResponse(w, http.StatusCreated, contracts.Chat{
|
||||
Id: resp.ID,
|
||||
Title: resp.Title,
|
||||
MemberIds: resp.MemberIDs,
|
||||
CreatedAt: resp.CreatedAt,
|
||||
})
|
||||
}
|
||||
|
||||
func (h *ChatHandler) Get(w http.ResponseWriter, r *http.Request) {
|
||||
ctx := r.Context()
|
||||
|
||||
userData, err := framework.ParseToken(r, h.provider)
|
||||
if err != nil {
|
||||
framework.JSONError(ctx, w, err)
|
||||
return
|
||||
}
|
||||
|
||||
limit, afterID, ok := framework.PageParams(w, r)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
|
||||
if userData.UserID == uuid.Nil {
|
||||
framework.JSONError(ctx, w, apperr.New(apperr.CodeBadRequest, "invalid user id"))
|
||||
return
|
||||
}
|
||||
if afterID != nil && *afterID == uuid.Nil {
|
||||
framework.JSONError(ctx, w, apperr.New(apperr.CodeBadRequest, "invalid cursor"))
|
||||
return
|
||||
}
|
||||
|
||||
page, err := h.chat.ListForMember(ctx, dto.ChatFilters{
|
||||
UserID: userData.UserID,
|
||||
Limit: limit,
|
||||
AfterID: afterID,
|
||||
})
|
||||
if err != nil {
|
||||
framework.JSONError(ctx, w, err)
|
||||
return
|
||||
}
|
||||
|
||||
items := make([]contracts.Chat, 0, len(page.Items))
|
||||
for _, item := range page.Items {
|
||||
items = append(items, contracts.Chat{
|
||||
CreatedAt: item.CreatedAt,
|
||||
Id: item.ID,
|
||||
MemberIds: item.MemberIDs,
|
||||
Title: item.Title,
|
||||
})
|
||||
}
|
||||
|
||||
framework.JSONResponse(w, http.StatusOK, contracts.ChatPage{
|
||||
Items: items,
|
||||
NextCursor: cursorString(page.NextCursorID),
|
||||
})
|
||||
}
|
||||
|
||||
func (h *ChatHandler) GetByID(w http.ResponseWriter, r *http.Request) {
|
||||
ctx := r.Context()
|
||||
|
||||
userData, err := framework.ParseToken(r, h.provider)
|
||||
if err != nil {
|
||||
framework.JSONError(ctx, w, err)
|
||||
return
|
||||
}
|
||||
|
||||
chatID, err := framework.ParseIDFromPathParam(ctx, w, r, "chat_id")
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
|
||||
resp, err := h.chat.GetForMember(ctx, dto.ChatMember{
|
||||
UserID: userData.UserID,
|
||||
ChatID: chatID,
|
||||
})
|
||||
if err != nil {
|
||||
framework.JSONError(ctx, w, err)
|
||||
return
|
||||
}
|
||||
|
||||
framework.JSONResponse(w, http.StatusOK, contracts.Chat{
|
||||
CreatedAt: resp.CreatedAt,
|
||||
Id: resp.ID,
|
||||
MemberIds: resp.MemberIDs,
|
||||
Title: resp.Title,
|
||||
})
|
||||
}
|
||||
|
||||
func (h *ChatHandler) SendMessage(w http.ResponseWriter, r *http.Request) {
|
||||
ctx := r.Context()
|
||||
|
||||
userData, err := framework.ParseToken(r, h.provider)
|
||||
if err != nil {
|
||||
framework.JSONError(ctx, w, err)
|
||||
return
|
||||
}
|
||||
|
||||
chatID, err := framework.ParseIDFromPathParam(ctx, w, r, "chat_id")
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
|
||||
var req contracts.CreateMessage
|
||||
if !framework.Decode(w, r, &req) || !framework.Validate(w, r, h.validator, &req) {
|
||||
return
|
||||
}
|
||||
|
||||
if !validText(req.Text, 4000) {
|
||||
framework.JSONError(ctx, w, apperr.New(apperr.CodeBadRequest, "invalid message text"))
|
||||
return
|
||||
}
|
||||
|
||||
message, err := h.chat.CreateMessage(ctx, dto.CreateMessage{
|
||||
ChatID: chatID,
|
||||
SenderID: userData.UserID,
|
||||
Text: req.Text,
|
||||
})
|
||||
if err != nil {
|
||||
framework.JSONError(ctx, w, err)
|
||||
return
|
||||
}
|
||||
|
||||
framework.JSONResponse(w, http.StatusCreated, contracts.Message{
|
||||
Id: message.ID,
|
||||
ChatId: message.ChatID,
|
||||
SenderId: message.SenderID,
|
||||
Text: message.Text,
|
||||
CreatedAt: message.CreatedAt,
|
||||
})
|
||||
}
|
||||
|
||||
func (h *ChatHandler) GetMessages(w http.ResponseWriter, r *http.Request) {
|
||||
ctx := r.Context()
|
||||
|
||||
userData, err := framework.ParseToken(r, h.provider)
|
||||
if err != nil {
|
||||
framework.JSONError(ctx, w, err)
|
||||
return
|
||||
}
|
||||
|
||||
chatID, err := framework.ParseIDFromPathParam(ctx, w, r, "chat_id")
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
|
||||
limit, afterID, ok := framework.PageParams(w, r)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
|
||||
page, err := h.chat.ListForChat(ctx, dto.MessageFilters{
|
||||
ChatID: chatID,
|
||||
UserID: userData.UserID,
|
||||
Limit: limit,
|
||||
AfterID: afterID,
|
||||
})
|
||||
if err != nil {
|
||||
framework.JSONError(ctx, w, err)
|
||||
return
|
||||
}
|
||||
|
||||
items := make([]contracts.Message, 0, len(page.Items))
|
||||
for _, message := range page.Items {
|
||||
items = append(items, contracts.Message{
|
||||
Id: message.ID,
|
||||
ChatId: message.ChatID,
|
||||
SenderId: message.SenderID,
|
||||
Text: message.Text,
|
||||
CreatedAt: message.CreatedAt,
|
||||
})
|
||||
}
|
||||
framework.JSONResponse(w, http.StatusOK, contracts.MessagePage{Items: items, NextCursor: cursorString(page.NextCursorID)})
|
||||
}
|
||||
|
||||
func cursorString(id *uuid.UUID) *string {
|
||||
if id == nil {
|
||||
return nil
|
||||
}
|
||||
value := id.String()
|
||||
return &value
|
||||
}
|
||||
|
||||
func validText(value string, maxLength int) bool {
|
||||
return utf8.ValidString(value) && strings.TrimSpace(value) != "" && utf8.RuneCountInString(value) <= maxLength
|
||||
}
|
||||
@@ -0,0 +1,101 @@
|
||||
package http
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"log/slog"
|
||||
"net"
|
||||
"net/http"
|
||||
"sync/atomic"
|
||||
|
||||
"gitea.privcloud.tech/mtusi2026/internal/config"
|
||||
"gitea.privcloud.tech/mtusi2026/internal/pkg/rest/router"
|
||||
)
|
||||
|
||||
type Server interface {
|
||||
ShouldBeRunning() bool
|
||||
Ready() bool
|
||||
Start(ctx context.Context) error
|
||||
Stop(ctx context.Context) error
|
||||
}
|
||||
|
||||
type server struct {
|
||||
server http.Server
|
||||
cfg *config.Server
|
||||
ready atomic.Bool
|
||||
}
|
||||
|
||||
func New(cfg *config.Config, router router.Router) Server {
|
||||
s := server{
|
||||
server: http.Server{
|
||||
Addr: cfg.Server.BindAddress(),
|
||||
Handler: router,
|
||||
ReadTimeout: cfg.Server.ReadTimeout,
|
||||
WriteTimeout: cfg.Server.WriteTimeout,
|
||||
IdleTimeout: cfg.Server.IdleTimeout,
|
||||
},
|
||||
cfg: cfg.Server,
|
||||
ready: atomic.Bool{},
|
||||
}
|
||||
|
||||
if err := s.validate(); err != nil {
|
||||
panic(err)
|
||||
}
|
||||
|
||||
return &s
|
||||
}
|
||||
|
||||
func (s *server) Start(_ context.Context) error {
|
||||
if !s.ShouldBeRunning() {
|
||||
slog.Info("server should not be running: skip starting")
|
||||
return nil
|
||||
}
|
||||
listener, err := net.Listen("tcp", s.server.Addr)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
s.ready.Store(true)
|
||||
go func() {
|
||||
defer s.ready.Store(false)
|
||||
if err := s.server.Serve(listener); err != nil &&
|
||||
!errors.Is(err, http.ErrServerClosed) {
|
||||
slog.Error("rest server failed", "error", err)
|
||||
}
|
||||
}()
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *server) Stop(ctx context.Context) error {
|
||||
if !s.ShouldBeRunning() {
|
||||
slog.Info("server should not be running: skip stopping")
|
||||
return nil
|
||||
}
|
||||
|
||||
slog.Info("shutting down rest server...", "address", s.server.Addr)
|
||||
s.ready.Store(false)
|
||||
if err := s.server.Shutdown(ctx); err != nil {
|
||||
slog.Error("rest server shutdown failed", "error", err)
|
||||
return err
|
||||
}
|
||||
slog.Info("rest server shutdown successfully")
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *server) ShouldBeRunning() bool {
|
||||
return s.cfg.Enabled
|
||||
}
|
||||
|
||||
func (s *server) Ready() bool {
|
||||
return s.ready.Load()
|
||||
}
|
||||
|
||||
func (s *server) validate() error {
|
||||
if s.cfg == nil {
|
||||
slog.Error("failed to validate server: provided nil config")
|
||||
return errors.New("failed to validate server: provided nil config")
|
||||
}
|
||||
|
||||
slog.Info("server successfully validated")
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,5 @@
|
||||
package http
|
||||
|
||||
type Handler interface {
|
||||
RegisterRoutes()
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
package http
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
|
||||
"gitea.privcloud.tech/mtusi2026/internal/gen/contracts"
|
||||
"gitea.privcloud.tech/mtusi2026/internal/pkg/apperr"
|
||||
"gitea.privcloud.tech/mtusi2026/internal/pkg/rest/framework"
|
||||
"gitea.privcloud.tech/mtusi2026/internal/pkg/rest/router"
|
||||
)
|
||||
|
||||
type HealthHandler struct {
|
||||
router router.Router
|
||||
server Server
|
||||
}
|
||||
|
||||
func NewHealthHandler(r router.Router, server Server) Handler {
|
||||
return &HealthHandler{
|
||||
router: r,
|
||||
server: server,
|
||||
}
|
||||
}
|
||||
|
||||
func (h *HealthHandler) RegisterRoutes() {
|
||||
h.router.Public(http.MethodGet, "/health/ready", h.Ready)
|
||||
h.router.Public(http.MethodGet, "/health/live", h.Live)
|
||||
}
|
||||
|
||||
func (h *HealthHandler) Live(w http.ResponseWriter, _ *http.Request) {
|
||||
framework.JSONResponse(w, http.StatusOK, contracts.Health{Status: contracts.Ok})
|
||||
}
|
||||
|
||||
func (h *HealthHandler) Ready(w http.ResponseWriter, r *http.Request) {
|
||||
if !h.server.Ready() {
|
||||
framework.JSONError(r.Context(), w, apperr.New(apperr.CodeUnavailable, "server is not ready"))
|
||||
return
|
||||
}
|
||||
framework.JSONResponse(w, http.StatusOK, contracts.Health{Status: contracts.Ok})
|
||||
}
|
||||
@@ -0,0 +1 @@
|
||||
package http
|
||||
@@ -0,0 +1,113 @@
|
||||
package http
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"regexp"
|
||||
"strings"
|
||||
"unicode/utf8"
|
||||
|
||||
"github.com/google/uuid"
|
||||
|
||||
"gitea.privcloud.tech/mtusi2026/internal/dto"
|
||||
"gitea.privcloud.tech/mtusi2026/internal/gen/contracts"
|
||||
"gitea.privcloud.tech/mtusi2026/internal/pkg/apperr"
|
||||
"gitea.privcloud.tech/mtusi2026/internal/pkg/auth/jwtprovider"
|
||||
"gitea.privcloud.tech/mtusi2026/internal/pkg/rest/framework"
|
||||
"gitea.privcloud.tech/mtusi2026/internal/pkg/rest/router"
|
||||
"gitea.privcloud.tech/mtusi2026/internal/pkg/validator"
|
||||
"gitea.privcloud.tech/mtusi2026/internal/service/user"
|
||||
)
|
||||
|
||||
type UserHandler struct {
|
||||
router router.Router
|
||||
provider jwtprovider.Provider
|
||||
validator *validator.ValidatorImpl
|
||||
|
||||
user user.API
|
||||
}
|
||||
|
||||
func NewUserHandler(r router.Router, provider jwtprovider.Provider, v *validator.ValidatorImpl, api user.API) Handler {
|
||||
return &UserHandler{
|
||||
router: r,
|
||||
provider: provider,
|
||||
validator: v,
|
||||
user: api,
|
||||
}
|
||||
}
|
||||
|
||||
var usernamePattern = regexp.MustCompile(`^[a-z0-9_]{3,32}$`)
|
||||
|
||||
func (h *UserHandler) RegisterRoutes() {
|
||||
h.router.Public(http.MethodPost, "/api/v1/users", h.Create)
|
||||
h.router.Private(http.MethodGet, "/api/v1/users/me", h.GetMe)
|
||||
}
|
||||
|
||||
func (h *UserHandler) Create(w http.ResponseWriter, r *http.Request) {
|
||||
ctx := r.Context()
|
||||
|
||||
var req contracts.CreateUser
|
||||
if !framework.Decode(w, r, &req) || !framework.Validate(w, r, h.validator, &req) {
|
||||
return
|
||||
}
|
||||
|
||||
toCreate := dto.CreateUser{
|
||||
Username: req.Username,
|
||||
DisplayName: req.DisplayName,
|
||||
}
|
||||
|
||||
if req.Password != nil {
|
||||
toCreate.Password = *req.Password
|
||||
}
|
||||
|
||||
if !usernamePattern.MatchString(req.Username) || !utf8.ValidString(req.DisplayName) ||
|
||||
strings.TrimSpace(req.DisplayName) == "" || utf8.RuneCountInString(req.DisplayName) > 100 {
|
||||
framework.JSONError(ctx, w, apperr.New(apperr.CodeBadRequest, "invalid user fields"))
|
||||
return
|
||||
}
|
||||
passwordLen := utf8.RuneCountInString(toCreate.Password)
|
||||
if !utf8.ValidString(toCreate.Password) || strings.TrimSpace(toCreate.Password) == "" || passwordLen < 12 || passwordLen > 128 {
|
||||
framework.JSONError(ctx, w, apperr.New(apperr.CodeBadRequest, "invalid password"))
|
||||
return
|
||||
}
|
||||
|
||||
resp, err := h.user.Create(ctx, toCreate)
|
||||
if err != nil {
|
||||
framework.JSONError(ctx, w, err)
|
||||
return
|
||||
}
|
||||
|
||||
framework.JSONResponse(w, http.StatusCreated, contracts.User{
|
||||
CreatedAt: resp.CreatedAt,
|
||||
DisplayName: resp.DisplayName,
|
||||
Id: resp.ID,
|
||||
Username: resp.Username,
|
||||
})
|
||||
}
|
||||
|
||||
func (h *UserHandler) GetMe(w http.ResponseWriter, r *http.Request) {
|
||||
ctx := r.Context()
|
||||
|
||||
userData, err := framework.ParseToken(r, h.provider)
|
||||
if err != nil {
|
||||
framework.JSONError(ctx, w, err)
|
||||
return
|
||||
}
|
||||
|
||||
if userData.UserID == uuid.Nil {
|
||||
framework.JSONError(ctx, w, apperr.New(apperr.CodeBadRequest, "invalid user id"))
|
||||
return
|
||||
}
|
||||
|
||||
resp, err := h.user.GetByID(ctx, userData.UserID)
|
||||
if err != nil {
|
||||
framework.JSONError(ctx, w, err)
|
||||
return
|
||||
}
|
||||
|
||||
framework.JSONResponse(w, http.StatusOK, contracts.User{
|
||||
CreatedAt: resp.CreatedAt,
|
||||
DisplayName: resp.DisplayName,
|
||||
Id: resp.ID,
|
||||
Username: resp.Username,
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,107 @@
|
||||
package inmemory
|
||||
|
||||
import (
|
||||
"log/slog"
|
||||
"sync/atomic"
|
||||
"unsafe"
|
||||
)
|
||||
|
||||
type Cache[K comparable, V any] interface {
|
||||
Name() string
|
||||
GetAll() map[K]V
|
||||
GetList() []V
|
||||
Get(key K) (value V, ok bool)
|
||||
Find(predicate func(K, V) bool) []V
|
||||
}
|
||||
|
||||
type CopyAndWriteCache[K comparable, V any] struct {
|
||||
name string
|
||||
data unsafe.Pointer
|
||||
}
|
||||
|
||||
func NewCopyAndWriteCache[K comparable, V any](
|
||||
name string,
|
||||
) *CopyAndWriteCache[K, V] {
|
||||
c := CopyAndWriteCache[K, V]{
|
||||
name: name,
|
||||
}
|
||||
|
||||
emptyMap := make(map[K]V)
|
||||
atomic.StorePointer(&c.data, unsafe.Pointer(&emptyMap))
|
||||
|
||||
slog.Info("cache initialized", "name", name)
|
||||
|
||||
return &c
|
||||
}
|
||||
|
||||
func (c *CopyAndWriteCache[K, V]) Name() string {
|
||||
return c.name
|
||||
}
|
||||
|
||||
func (c *CopyAndWriteCache[K, V]) GetAll() map[K]V {
|
||||
ptr := atomic.LoadPointer(&c.data)
|
||||
if ptr == nil {
|
||||
return make(map[K]V)
|
||||
}
|
||||
|
||||
m := *(*map[K]V)(ptr)
|
||||
|
||||
out := make(map[K]V, len(m))
|
||||
for k, v := range m {
|
||||
out[k] = v
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
func (c *CopyAndWriteCache[K, V]) GetList() []V {
|
||||
records := c.GetAll()
|
||||
out := make([]V, 0, len(records))
|
||||
for _, record := range records {
|
||||
out = append(out, record)
|
||||
}
|
||||
|
||||
return out
|
||||
}
|
||||
|
||||
func (c *CopyAndWriteCache[K, V]) Get(key K) (value V, ok bool) {
|
||||
ptr := atomic.LoadPointer(&c.data)
|
||||
if ptr == nil {
|
||||
var zero V
|
||||
return zero, false
|
||||
}
|
||||
|
||||
m := *(*map[K]V)(ptr)
|
||||
v, ok := m[key]
|
||||
return v, ok
|
||||
}
|
||||
|
||||
func (c *CopyAndWriteCache[K, V]) Find(predicate func(K, V) bool) []V {
|
||||
ptr := atomic.LoadPointer(&c.data)
|
||||
if ptr == nil {
|
||||
return []V{}
|
||||
}
|
||||
|
||||
m := *(*map[K]V)(ptr)
|
||||
|
||||
var result []V
|
||||
for key, value := range m {
|
||||
if predicate(key, value) {
|
||||
result = append(result, value)
|
||||
}
|
||||
}
|
||||
|
||||
return result
|
||||
}
|
||||
|
||||
func (c *CopyAndWriteCache[K, V]) Store(key K, value V) bool {
|
||||
ptr := atomic.LoadPointer(&c.data)
|
||||
if ptr == nil {
|
||||
return false
|
||||
}
|
||||
|
||||
m := *(*map[K]V)(ptr)
|
||||
|
||||
m[key] = value
|
||||
|
||||
return true
|
||||
}
|
||||
@@ -0,0 +1,78 @@
|
||||
package outside
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
|
||||
"gitea.privcloud.tech/mtusi2026/internal/dto"
|
||||
"gitea.privcloud.tech/mtusi2026/internal/pkg/apperr"
|
||||
"gitea.privcloud.tech/mtusi2026/internal/pkg/cache"
|
||||
)
|
||||
|
||||
const (
|
||||
// chatRedisKey equals "chat:{chat_id}" path
|
||||
chatRedisKey = "chat:%s"
|
||||
)
|
||||
|
||||
type ChatCache struct {
|
||||
client *cache.Client
|
||||
}
|
||||
|
||||
func NewChatCache(client *cache.Client) *ChatCache {
|
||||
return &ChatCache{
|
||||
client: client,
|
||||
}
|
||||
}
|
||||
|
||||
type chat struct {
|
||||
ID uuid.UUID `json:"id"`
|
||||
Title string `json:"title"`
|
||||
MemberIDs []uuid.UUID `json:"member_ids"`
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
}
|
||||
|
||||
func (r *ChatCache) Create(ctx context.Context, req dto.Chat) error {
|
||||
data, err := json.Marshal(chat{
|
||||
ID: req.ID,
|
||||
Title: req.Title,
|
||||
MemberIDs: req.MemberIDs,
|
||||
CreatedAt: req.CreatedAt,
|
||||
})
|
||||
if err != nil {
|
||||
return apperr.Wrap(err, apperr.CodeInternal, "failed to marshal chat cache")
|
||||
}
|
||||
|
||||
ctx, cancel := context.WithTimeout(ctx, cache.OperationTimeout)
|
||||
defer cancel()
|
||||
err = r.client.Set(ctx, fmt.Sprintf(chatRedisKey, req.ID), data, 0).Err()
|
||||
if err != nil {
|
||||
return apperr.WrapRedis(err, "failed to create chat cache")
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (r *ChatCache) Get(ctx context.Context, chatID uuid.UUID) (*dto.Chat, error) {
|
||||
ctx, cancel := context.WithTimeout(ctx, cache.OperationTimeout)
|
||||
defer cancel()
|
||||
data, err := r.client.Get(ctx, fmt.Sprintf(chatRedisKey, chatID.String())).Bytes()
|
||||
if err != nil {
|
||||
return nil, apperr.WrapRedis(err, "failed to read chat cache")
|
||||
}
|
||||
|
||||
var item chat
|
||||
if err = json.Unmarshal(data, &item); err != nil {
|
||||
return nil, apperr.Wrap(err, apperr.CodeInternal, "failed to unmarshal chat cache")
|
||||
}
|
||||
|
||||
return &dto.Chat{
|
||||
ID: item.ID,
|
||||
Title: item.Title,
|
||||
MemberIDs: item.MemberIDs,
|
||||
CreatedAt: item.CreatedAt,
|
||||
}, nil
|
||||
}
|
||||
@@ -0,0 +1,91 @@
|
||||
package storage
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
|
||||
"github.com/google/uuid"
|
||||
"github.com/jackc/pgerrcode"
|
||||
"github.com/jackc/pgx/v5"
|
||||
"github.com/jackc/pgx/v5/pgconn"
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
|
||||
"gitea.privcloud.tech/mtusi2026/internal/dto"
|
||||
"gitea.privcloud.tech/mtusi2026/internal/pkg/apperr"
|
||||
)
|
||||
|
||||
type ChatsRepo struct {
|
||||
pool *pgxpool.Pool
|
||||
}
|
||||
|
||||
func NewChatsRepo(pool *pgxpool.Pool) *ChatsRepo {
|
||||
return &ChatsRepo{pool: pool}
|
||||
}
|
||||
|
||||
func (r *ChatsRepo) CreateTx(ctx context.Context, tx pgx.Tx, req dto.Chat) error {
|
||||
const insertChat = `INSERT INTO chats (id, title, created_at) VALUES ($1, $2, $3)`
|
||||
if _, err := tx.Exec(ctx, insertChat, req.ID, req.Title, req.CreatedAt); err != nil {
|
||||
return apperr.WrapPostgres(err, "failed to create chat")
|
||||
}
|
||||
const insertMembers = `INSERT INTO chat_members (chat_id, user_id)
|
||||
SELECT $1, user_id FROM unnest($2::uuid[]) AS members(user_id)`
|
||||
if _, err := tx.Exec(ctx, insertMembers, req.ID, req.MemberIDs); err != nil {
|
||||
if pgErr, ok := errors.AsType[*pgconn.PgError](err); ok &&
|
||||
pgErr.Code == pgerrcode.ForeignKeyViolation && pgErr.ConstraintName == "chat_members_user_fk" {
|
||||
return apperr.Wrap(err, apperr.CodeBadRequest, "unknown chat member")
|
||||
}
|
||||
return apperr.WrapPostgres(err, "failed to create chat members")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (r *ChatsRepo) GetForMember(ctx context.Context, req dto.ChatMember) (*dto.Chat, error) {
|
||||
const query = `SELECT c.id, c.title, c.created_at,
|
||||
ARRAY(SELECT m.user_id FROM chat_members m WHERE m.chat_id = c.id ORDER BY m.user_id)
|
||||
FROM chats c
|
||||
WHERE c.id = $1
|
||||
AND EXISTS (SELECT 1 FROM chat_members access WHERE access.chat_id = c.id AND access.user_id = $2)`
|
||||
return scanChat(r.pool.QueryRow(ctx, query, req.ChatID, req.UserID))
|
||||
}
|
||||
|
||||
func (r *ChatsRepo) ListForMember(ctx context.Context, userID uuid.UUID, page dto.PageQuery) ([]dto.Chat, error) {
|
||||
query := `WITH page AS MATERIALIZED (
|
||||
SELECT c.id, c.title, c.created_at
|
||||
FROM chats c JOIN chat_members access ON access.chat_id = c.id
|
||||
WHERE access.user_id = $1`
|
||||
args := []any{userID, page.Limit}
|
||||
if page.After != nil {
|
||||
query += ` AND (c.created_at, c.id) > ($3, $4)`
|
||||
args = append(args, page.After.CreatedAt, page.After.ID)
|
||||
}
|
||||
query += ` ORDER BY c.created_at, c.id LIMIT $2
|
||||
)
|
||||
SELECT p.id, p.title, p.created_at,
|
||||
ARRAY(SELECT m.user_id FROM chat_members m WHERE m.chat_id = p.id ORDER BY m.user_id)
|
||||
FROM page p ORDER BY p.created_at, p.id`
|
||||
rows, err := r.pool.Query(ctx, query, args...)
|
||||
if err != nil {
|
||||
return nil, apperr.WrapPostgres(err, "failed to list chats")
|
||||
}
|
||||
defer rows.Close()
|
||||
chats := make([]dto.Chat, 0)
|
||||
for rows.Next() {
|
||||
chat, err := scanChat(rows)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
chats = append(chats, *chat)
|
||||
}
|
||||
if err = rows.Err(); err != nil {
|
||||
return nil, apperr.WrapPostgres(err, "failed to list chats")
|
||||
}
|
||||
return chats, nil
|
||||
}
|
||||
|
||||
func scanChat(row pgx.Row) (*dto.Chat, error) {
|
||||
var chat dto.Chat
|
||||
if err := row.Scan(&chat.ID, &chat.Title, &chat.CreatedAt, &chat.MemberIDs); err != nil {
|
||||
return nil, apperr.WrapPostgres(err, "failed to get chat")
|
||||
}
|
||||
return &chat, nil
|
||||
}
|
||||
@@ -0,0 +1,75 @@
|
||||
package storage
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
|
||||
"github.com/google/uuid"
|
||||
"github.com/jackc/pgerrcode"
|
||||
"github.com/jackc/pgx/v5"
|
||||
"github.com/jackc/pgx/v5/pgconn"
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
|
||||
"gitea.privcloud.tech/mtusi2026/internal/dto"
|
||||
"gitea.privcloud.tech/mtusi2026/internal/pkg/apperr"
|
||||
)
|
||||
|
||||
type MessagesRepo struct {
|
||||
pool *pgxpool.Pool
|
||||
}
|
||||
|
||||
func NewMessagesRepo(pool *pgxpool.Pool) *MessagesRepo {
|
||||
return &MessagesRepo{pool: pool}
|
||||
}
|
||||
|
||||
func (r *MessagesRepo) Create(ctx context.Context, req dto.Message) error {
|
||||
const query = `INSERT INTO messages (id, chat_id, sender_id, text, created_at) VALUES ($1, $2, $3, $4, $5)`
|
||||
if _, err := r.pool.Exec(ctx, query, req.ID, req.ChatID, req.SenderID, req.Text, req.CreatedAt); err != nil {
|
||||
if pgErr, ok := errors.AsType[*pgconn.PgError](err); ok &&
|
||||
pgErr.Code == pgerrcode.ForeignKeyViolation && pgErr.ConstraintName == "messages_sender_member_fk" {
|
||||
return apperr.Wrap(err, apperr.CodeNotFound, "chat not found")
|
||||
}
|
||||
return apperr.WrapPostgres(err, "failed to create message")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (r *MessagesRepo) GetByIDForChat(ctx context.Context, chatID, messageID uuid.UUID) (*dto.Message, error) {
|
||||
const query = `SELECT id, chat_id, sender_id, text, created_at FROM messages WHERE chat_id = $1 AND id = $2`
|
||||
return scanMessage(r.pool.QueryRow(ctx, query, chatID, messageID))
|
||||
}
|
||||
|
||||
func (r *MessagesRepo) ListForChat(ctx context.Context, chatID uuid.UUID, page dto.PageQuery) ([]dto.Message, error) {
|
||||
query := `SELECT id, chat_id, sender_id, text, created_at FROM messages WHERE chat_id = $1`
|
||||
args := []any{chatID, page.Limit}
|
||||
if page.After != nil {
|
||||
query += ` AND (created_at, id) > ($3, $4)`
|
||||
args = append(args, page.After.CreatedAt, page.After.ID)
|
||||
}
|
||||
query += ` ORDER BY created_at, id LIMIT $2`
|
||||
rows, err := r.pool.Query(ctx, query, args...)
|
||||
if err != nil {
|
||||
return nil, apperr.WrapPostgres(err, "failed to list messages")
|
||||
}
|
||||
defer rows.Close()
|
||||
messages := make([]dto.Message, 0)
|
||||
for rows.Next() {
|
||||
message, err := scanMessage(rows)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
messages = append(messages, *message)
|
||||
}
|
||||
if err = rows.Err(); err != nil {
|
||||
return nil, apperr.WrapPostgres(err, "failed to list messages")
|
||||
}
|
||||
return messages, nil
|
||||
}
|
||||
|
||||
func scanMessage(row pgx.Row) (*dto.Message, error) {
|
||||
var message dto.Message
|
||||
if err := row.Scan(&message.ID, &message.ChatID, &message.SenderID, &message.Text, &message.CreatedAt); err != nil {
|
||||
return nil, apperr.WrapPostgres(err, "failed to get message")
|
||||
}
|
||||
return &message, nil
|
||||
}
|
||||
@@ -0,0 +1,193 @@
|
||||
package storage
|
||||
|
||||
import (
|
||||
"context"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
"github.com/jackc/pgx/v5"
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
|
||||
"gitea.privcloud.tech/mtusi2026/internal/dto"
|
||||
"gitea.privcloud.tech/mtusi2026/internal/pkg/apperr"
|
||||
"gitea.privcloud.tech/mtusi2026/internal/pkg/postgres"
|
||||
)
|
||||
|
||||
type RefreshTokensRepo struct {
|
||||
pool *pgxpool.Pool
|
||||
}
|
||||
|
||||
func NewRefreshTokensRepo(pool *pgxpool.Pool) *RefreshTokensRepo {
|
||||
return &RefreshTokensRepo{
|
||||
pool: pool,
|
||||
}
|
||||
}
|
||||
|
||||
func (r *RefreshTokensRepo) Create(ctx context.Context, req dto.StoredRefreshToken) error {
|
||||
return r.create(ctx, r.pool, req)
|
||||
}
|
||||
|
||||
func (r *RefreshTokensRepo) CreateTx(ctx context.Context, tx pgx.Tx, req dto.StoredRefreshToken) error {
|
||||
return r.create(ctx, tx, req)
|
||||
}
|
||||
|
||||
func (r *RefreshTokensRepo) GetByID(ctx context.Context, id uuid.UUID) (*dto.StoredRefreshToken, error) {
|
||||
return r.getByID(ctx, r.pool, id, false)
|
||||
}
|
||||
|
||||
func (r *RefreshTokensRepo) GetByIDTx(ctx context.Context, tx pgx.Tx, id uuid.UUID) (*dto.StoredRefreshToken, error) {
|
||||
return r.getByID(ctx, tx, id, false)
|
||||
}
|
||||
|
||||
func (r *RefreshTokensRepo) GetByIDForUpdate(ctx context.Context, id uuid.UUID) (*dto.StoredRefreshToken, error) {
|
||||
return r.getByID(ctx, r.pool, id, true)
|
||||
}
|
||||
|
||||
func (r *RefreshTokensRepo) GetByIDForUpdateTx(ctx context.Context, tx pgx.Tx, id uuid.UUID) (*dto.StoredRefreshToken, error) {
|
||||
return r.getByID(ctx, tx, id, true)
|
||||
}
|
||||
|
||||
func (r *RefreshTokensRepo) Revoke(ctx context.Context, req dto.RevokeRefreshToken) error {
|
||||
return r.revoke(ctx, r.pool, req)
|
||||
}
|
||||
|
||||
func (r *RefreshTokensRepo) RevokeTx(ctx context.Context, tx pgx.Tx, req dto.RevokeRefreshToken) error {
|
||||
return r.revoke(ctx, tx, req)
|
||||
}
|
||||
|
||||
func (r *RefreshTokensRepo) RevokeAllByUserID(ctx context.Context, req dto.RevokeRefreshTokensByUserID) error {
|
||||
return r.revokeAllByUserID(ctx, r.pool, req)
|
||||
}
|
||||
|
||||
func (r *RefreshTokensRepo) RevokeAllByUserIDTx(ctx context.Context, tx pgx.Tx, req dto.RevokeRefreshTokensByUserID) error {
|
||||
return r.revokeAllByUserID(ctx, tx, req)
|
||||
}
|
||||
|
||||
func (r *RefreshTokensRepo) DeleteExpired(ctx context.Context) error {
|
||||
const query = `
|
||||
DELETE FROM refresh_tokens
|
||||
WHERE expires_at < $1`
|
||||
|
||||
_, err := r.pool.Exec(ctx, query, time.Now())
|
||||
if err != nil {
|
||||
return apperr.WrapPostgres(err, "failed to delete expired refresh tokens")
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (r *RefreshTokensRepo) create(ctx context.Context, conn postgres.Conn, req dto.StoredRefreshToken) error {
|
||||
const query = `INSERT INTO refresh_tokens (id,
|
||||
user_id,
|
||||
token_hash,
|
||||
user_agent,
|
||||
ip_address,
|
||||
role,
|
||||
expires_at,
|
||||
created_at)
|
||||
VALUES ($1, $2, $3, $4, $5, $6, $7, $8)`
|
||||
|
||||
ct, err := conn.Exec(
|
||||
ctx,
|
||||
query,
|
||||
req.ID,
|
||||
req.UserID,
|
||||
req.TokenHash,
|
||||
req.UserAgent,
|
||||
req.IPAddress,
|
||||
req.Role,
|
||||
req.ExpiresAt,
|
||||
req.CreatedAt,
|
||||
)
|
||||
if err != nil {
|
||||
return apperr.WrapPostgres(err, "failed to create refresh token")
|
||||
}
|
||||
|
||||
if ct.RowsAffected() == 0 {
|
||||
return apperr.New(apperr.CodeAlreadyExists, "refresh token already exists")
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (r *RefreshTokensRepo) getByID(ctx context.Context, conn postgres.Conn, id uuid.UUID, lock bool) (*dto.StoredRefreshToken, error) {
|
||||
const query = `SELECT id,
|
||||
user_id,
|
||||
token_hash,
|
||||
user_agent,
|
||||
ip_address,
|
||||
role,
|
||||
expires_at,
|
||||
revoked_at,
|
||||
created_at
|
||||
FROM refresh_tokens
|
||||
WHERE id = $1`
|
||||
const queryLock = `SELECT id,
|
||||
user_id,
|
||||
token_hash,
|
||||
user_agent,
|
||||
ip_address,
|
||||
role,
|
||||
expires_at,
|
||||
revoked_at,
|
||||
created_at
|
||||
FROM refresh_tokens
|
||||
WHERE id = $1 FOR UPDATE`
|
||||
|
||||
use := query
|
||||
if lock {
|
||||
use = queryLock
|
||||
}
|
||||
|
||||
var token dto.StoredRefreshToken
|
||||
err := conn.QueryRow(ctx, use, id).Scan(
|
||||
&token.ID,
|
||||
&token.UserID,
|
||||
&token.TokenHash,
|
||||
&token.UserAgent,
|
||||
&token.IPAddress,
|
||||
&token.Role,
|
||||
&token.ExpiresAt,
|
||||
&token.RevokedAt,
|
||||
&token.CreatedAt,
|
||||
)
|
||||
if err != nil {
|
||||
return nil, apperr.WrapPostgres(err, "failed to get refresh by id")
|
||||
}
|
||||
|
||||
return &token, nil
|
||||
}
|
||||
|
||||
func (r *RefreshTokensRepo) revoke(ctx context.Context, conn postgres.Conn, req dto.RevokeRefreshToken) error {
|
||||
const query = `
|
||||
UPDATE refresh_tokens
|
||||
SET revoked_at = $2
|
||||
WHERE id = $1
|
||||
AND revoked_at IS NULL`
|
||||
|
||||
ct, err := conn.Exec(ctx, query, req.ID, req.RevokedAt)
|
||||
if err != nil {
|
||||
return apperr.WrapPostgres(err, "failed to revoke refresh token")
|
||||
}
|
||||
|
||||
if ct.RowsAffected() == 0 {
|
||||
return apperr.New(apperr.CodeNotFound, "refresh token not found")
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (r *RefreshTokensRepo) revokeAllByUserID(ctx context.Context, conn postgres.Conn, req dto.RevokeRefreshTokensByUserID) error {
|
||||
const query = `
|
||||
UPDATE refresh_tokens
|
||||
SET revoked_at = $2
|
||||
WHERE user_id = $1
|
||||
AND revoked_at IS NULL`
|
||||
|
||||
_, err := conn.Exec(ctx, query, req.UserID, req.RevokedAt)
|
||||
if err != nil {
|
||||
return apperr.WrapPostgres(err, "failed to revoke refresh tokens")
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,103 @@
|
||||
package storage
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
|
||||
"github.com/google/uuid"
|
||||
"github.com/jackc/pgerrcode"
|
||||
"github.com/jackc/pgx/v5"
|
||||
"github.com/jackc/pgx/v5/pgconn"
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
|
||||
"gitea.privcloud.tech/mtusi2026/internal/dto"
|
||||
"gitea.privcloud.tech/mtusi2026/internal/pkg/apperr"
|
||||
"gitea.privcloud.tech/mtusi2026/internal/pkg/postgres"
|
||||
)
|
||||
|
||||
type UsersRepo struct {
|
||||
pool *pgxpool.Pool
|
||||
}
|
||||
|
||||
func NewUsersRepo(pool *pgxpool.Pool) *UsersRepo {
|
||||
return &UsersRepo{pool: pool}
|
||||
}
|
||||
|
||||
func (r *UsersRepo) Create(ctx context.Context, req dto.CreateStoredUser) error {
|
||||
return r.create(ctx, r.pool, req)
|
||||
}
|
||||
|
||||
func (r *UsersRepo) CreateTx(ctx context.Context, tx pgx.Tx, req dto.CreateStoredUser) error {
|
||||
return r.create(ctx, tx, req)
|
||||
}
|
||||
|
||||
func (r *UsersRepo) GetByID(ctx context.Context, id uuid.UUID) (*dto.User, error) {
|
||||
return r.getByID(ctx, r.pool, id)
|
||||
}
|
||||
|
||||
func (r *UsersRepo) GetByIDTx(ctx context.Context, tx pgx.Tx, id uuid.UUID) (*dto.User, error) {
|
||||
return r.getByID(ctx, tx, id)
|
||||
}
|
||||
|
||||
func (r *UsersRepo) GetByUsername(ctx context.Context, username string) (*dto.User, error) {
|
||||
const query = `SELECT id, username, name, created_at FROM users WHERE username = $1`
|
||||
return scanUser(r.pool.QueryRow(ctx, query, username))
|
||||
}
|
||||
|
||||
func (r *UsersRepo) GetCredentialsByUsername(ctx context.Context, username string) (*dto.UserCredentials, error) {
|
||||
const query = `SELECT id, username, name, created_at, password_hash FROM users WHERE username = $1`
|
||||
|
||||
var credentials dto.UserCredentials
|
||||
err := r.pool.QueryRow(ctx, query, username).Scan(
|
||||
&credentials.User.ID,
|
||||
&credentials.User.Username,
|
||||
&credentials.User.DisplayName,
|
||||
&credentials.User.CreatedAt,
|
||||
&credentials.PasswordHash,
|
||||
)
|
||||
if err != nil {
|
||||
return nil, apperr.WrapPostgres(err, "failed to get user credentials")
|
||||
}
|
||||
return &credentials, nil
|
||||
}
|
||||
|
||||
func (r *UsersRepo) Delete(ctx context.Context, id uuid.UUID) error {
|
||||
const query = `DELETE FROM users WHERE id = $1`
|
||||
|
||||
ct, err := r.pool.Exec(ctx, query, id)
|
||||
if err != nil {
|
||||
return apperr.WrapPostgres(err, "failed to delete user")
|
||||
}
|
||||
if ct.RowsAffected() == 0 {
|
||||
return apperr.New(apperr.CodeNotFound, "user not found")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (r *UsersRepo) create(ctx context.Context, conn postgres.Conn, req dto.CreateStoredUser) error {
|
||||
const query = `INSERT INTO users (id, username, name, password_hash, created_at, updated_at)
|
||||
VALUES ($1, $2, $3, $4, $5, $6)`
|
||||
|
||||
_, err := conn.Exec(ctx, query, req.ID, req.Username, req.DisplayName, req.PasswordHash, req.CreatedAt, req.UpdatedAt)
|
||||
if err != nil {
|
||||
if pgErr, ok := errors.AsType[*pgconn.PgError](err); ok &&
|
||||
pgErr.Code == pgerrcode.UniqueViolation && pgErr.ConstraintName == "users_username_unique" {
|
||||
return apperr.Wrap(err, apperr.CodeConflict, "username already exists")
|
||||
}
|
||||
return apperr.WrapPostgres(err, "failed to create user")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (r *UsersRepo) getByID(ctx context.Context, conn postgres.Conn, id uuid.UUID) (*dto.User, error) {
|
||||
const query = `SELECT id, username, name, created_at FROM users WHERE id = $1`
|
||||
return scanUser(conn.QueryRow(ctx, query, id))
|
||||
}
|
||||
|
||||
func scanUser(row pgx.Row) (*dto.User, error) {
|
||||
var user dto.User
|
||||
if err := row.Scan(&user.ID, &user.Username, &user.DisplayName, &user.CreatedAt); err != nil {
|
||||
return nil, apperr.WrapPostgres(err, "failed to get user")
|
||||
}
|
||||
return &user, nil
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
package config
|
||||
|
||||
import "github.com/spf13/viper"
|
||||
|
||||
type Loader interface {
|
||||
loadConfig(v *viper.Viper) error
|
||||
}
|
||||
@@ -0,0 +1,63 @@
|
||||
package config
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"time"
|
||||
|
||||
"github.com/spf13/viper"
|
||||
|
||||
"gitea.privcloud.tech/mtusi2026/internal/pkg/types/environment"
|
||||
)
|
||||
|
||||
type Application struct {
|
||||
LogLevel string
|
||||
ShutdownTimeout time.Duration
|
||||
Environment environment.ApplicationEnvironment
|
||||
RequestRateLimit float64
|
||||
BurstRateLimit int
|
||||
RateLimitTTL time.Duration
|
||||
}
|
||||
|
||||
func (c *Application) Validate() error {
|
||||
environmentErr := c.Environment.Validate()
|
||||
|
||||
switch {
|
||||
case c.LogLevel == "":
|
||||
return wrapValidationError("application", errors.New("log_level cannot be empty in application config"))
|
||||
case c.ShutdownTimeout == 0:
|
||||
return wrapValidationError("application", errors.New("shutdown_timeout cannot be zero in application config"))
|
||||
case environmentErr != nil:
|
||||
return wrapValidationError("application", environmentErr)
|
||||
//case c.RequestRateLimit == 0:
|
||||
// return wrapValidationError("application", errors.New("request_rate_limit cannot be zero in application config"))
|
||||
//case c.BurstRateLimit == 0:
|
||||
// return wrapValidationError("application", errors.New("burst_rate_limit cannot be zero in application config"))
|
||||
//case c.RateLimitTTL == 0:
|
||||
// return wrapValidationError("application", errors.New("rate_limit_ttl cannot be zero in application config"))
|
||||
default:
|
||||
return nil
|
||||
}
|
||||
}
|
||||
|
||||
func (c *Application) loadConfig(v *viper.Viper) error {
|
||||
v.SetEnvPrefix("APPLICATION")
|
||||
c.LogLevel = v.GetString("LOG_LEVEL")
|
||||
c.ShutdownTimeout = v.GetDuration("SHUTDOWN_TIMEOUT")
|
||||
c.Environment = environment.ParseEnvironment(v.GetString("ENVIRONMENT"))
|
||||
// todo add cool value
|
||||
c.RequestRateLimit = v.GetFloat64("REQUEST_RATE_LIMIT")
|
||||
c.BurstRateLimit = v.GetInt("BURST_RATE_LIMIT")
|
||||
c.RateLimitTTL = v.GetDuration("RATE_LIMIT_TTL")
|
||||
return nil
|
||||
}
|
||||
|
||||
func (c *Application) copy() *Application {
|
||||
return &Application{
|
||||
LogLevel: c.LogLevel,
|
||||
ShutdownTimeout: c.ShutdownTimeout,
|
||||
Environment: c.Environment,
|
||||
RequestRateLimit: c.RequestRateLimit,
|
||||
BurstRateLimit: c.BurstRateLimit,
|
||||
RateLimitTTL: c.RateLimitTTL,
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,108 @@
|
||||
package config
|
||||
|
||||
import (
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/spf13/viper"
|
||||
"go.uber.org/multierr"
|
||||
|
||||
"gitea.privcloud.tech/mtusi2026/internal/pkg/types/environment"
|
||||
)
|
||||
|
||||
var defaultConfig = &Config{
|
||||
Server: &Server{
|
||||
Host: "localhost",
|
||||
Port: 8001,
|
||||
ReadTimeout: 10 * time.Second,
|
||||
WriteTimeout: 10 * time.Second,
|
||||
IdleTimeout: 10 * time.Second,
|
||||
ShutdownTimeout: 10 * time.Second,
|
||||
Enabled: false,
|
||||
},
|
||||
Postgres: &Postgres{
|
||||
Host: "localhost",
|
||||
Port: 5432,
|
||||
User: "postgres",
|
||||
Password: "postgres",
|
||||
Database: "postgres",
|
||||
VersionTable: "versions",
|
||||
RunMigrations: false,
|
||||
MaxConnections: 10,
|
||||
},
|
||||
Redis: &Redis{
|
||||
Host: "localhost",
|
||||
Port: 6379,
|
||||
Username: "",
|
||||
Password: "",
|
||||
DB: 0,
|
||||
},
|
||||
JWT: &JWT{
|
||||
AccessTokenLifetime: 4 * time.Hour,
|
||||
RefreshTokenLifetime: 24 * time.Hour,
|
||||
PublicKeyPath: "certs/private.pem",
|
||||
PrivateKeyPath: "certs/public.pem",
|
||||
},
|
||||
Application: &Application{
|
||||
LogLevel: "info",
|
||||
ShutdownTimeout: 10 * time.Second,
|
||||
Environment: environment.ApplicationEnvironmentDev,
|
||||
RequestRateLimit: 100,
|
||||
},
|
||||
}
|
||||
|
||||
type Config struct {
|
||||
Server *Server
|
||||
Postgres *Postgres
|
||||
Redis *Redis
|
||||
JWT *JWT
|
||||
Application *Application
|
||||
}
|
||||
|
||||
func New() (*Config, error) {
|
||||
v := viper.New()
|
||||
v.SetEnvKeyReplacer(strings.NewReplacer(".", "_"))
|
||||
v.AutomaticEnv()
|
||||
|
||||
cfg := defaultConfig.copy()
|
||||
|
||||
if err := cfg.loadConfig(v); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
if err := cfg.Validate(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return cfg, nil
|
||||
}
|
||||
|
||||
func (c *Config) Validate() error {
|
||||
return multierr.Combine(
|
||||
c.Server.Validate(),
|
||||
c.Postgres.Validate(),
|
||||
c.JWT.Validate(),
|
||||
c.Redis.Validate(),
|
||||
c.Application.Validate(),
|
||||
)
|
||||
}
|
||||
|
||||
func (c *Config) loadConfig(v *viper.Viper) error {
|
||||
return multierr.Combine(
|
||||
c.Postgres.loadConfig(v),
|
||||
c.Server.loadConfig(v),
|
||||
c.JWT.loadConfig(v),
|
||||
c.Redis.loadConfig(v),
|
||||
c.Application.loadConfig(v),
|
||||
)
|
||||
}
|
||||
|
||||
func (c *Config) copy() *Config {
|
||||
return &Config{
|
||||
Server: c.Server.copy(),
|
||||
Postgres: c.Postgres.copy(),
|
||||
Redis: c.Redis.copy(),
|
||||
JWT: c.JWT.copy(),
|
||||
Application: c.Application.copy(),
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,65 @@
|
||||
package config
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"net/http"
|
||||
"strings"
|
||||
|
||||
"github.com/spf13/viper"
|
||||
)
|
||||
|
||||
type Cookies struct {
|
||||
Enabled bool
|
||||
Domain string
|
||||
Path string
|
||||
Secure bool
|
||||
SameSite http.SameSite
|
||||
AllowedOrigins []string
|
||||
}
|
||||
|
||||
func (c *Cookies) Validate() error {
|
||||
switch {
|
||||
case c.Domain == "":
|
||||
return wrapValidationError("cookies", errors.New("domain cannot be empty"))
|
||||
case c.Path == "":
|
||||
return wrapValidationError("cookies", errors.New("path cannot be empty"))
|
||||
case c.SameSite == http.SameSiteDefaultMode:
|
||||
return wrapValidationError("cookies", errors.New("same_site_set_to_none_mode cannot be empty"))
|
||||
//case c.Enabled && !c.Secure:
|
||||
// return wrapValidationError("cookies", errors.New("if cookies_enabled equals true then cookies_secure must be true"))
|
||||
case c.AllowedOrigins == nil || len(c.AllowedOrigins) == 0:
|
||||
return wrapValidationError("cookies", errors.New("allowed_origins cannot be empty"))
|
||||
default:
|
||||
return nil
|
||||
}
|
||||
}
|
||||
|
||||
func (c *Cookies) loadConfig(v *viper.Viper) error {
|
||||
v.SetEnvPrefix("COOKIES")
|
||||
c.Enabled = v.GetBool("ENABLED")
|
||||
c.Domain = v.GetString("DOMAIN")
|
||||
c.Path = v.GetString("PATH")
|
||||
c.Secure = v.GetBool("SECURE")
|
||||
c.AllowedOrigins = v.GetStringSlice("ALLOWED_ORIGINS")
|
||||
sameSite := v.GetString("SAME_SITE")
|
||||
switch strings.ToLower(strings.TrimSpace(sameSite)) {
|
||||
case "strict":
|
||||
c.SameSite = http.SameSiteStrictMode
|
||||
case "none":
|
||||
c.SameSite = http.SameSiteNoneMode
|
||||
default:
|
||||
c.SameSite = http.SameSiteLaxMode
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (c *Cookies) copy() *Cookies {
|
||||
return &Cookies{
|
||||
Enabled: c.Enabled,
|
||||
Domain: c.Domain,
|
||||
Path: c.Path,
|
||||
Secure: c.Secure,
|
||||
SameSite: c.SameSite,
|
||||
AllowedOrigins: c.AllowedOrigins,
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,48 @@
|
||||
package config
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"time"
|
||||
|
||||
"github.com/spf13/viper"
|
||||
)
|
||||
|
||||
type JWT struct {
|
||||
AccessTokenLifetime time.Duration
|
||||
RefreshTokenLifetime time.Duration
|
||||
PublicKeyPath string
|
||||
PrivateKeyPath string
|
||||
}
|
||||
|
||||
func (c *JWT) Validate() error {
|
||||
switch {
|
||||
case c.AccessTokenLifetime == 0:
|
||||
return wrapValidationError("jwt", errors.New("access_token_lifetime cannot be empty"))
|
||||
case c.RefreshTokenLifetime == 0:
|
||||
return wrapValidationError("jwt", errors.New("refresh_token_lifetime cannot be empty"))
|
||||
case c.PrivateKeyPath == "":
|
||||
return wrapValidationError("jwt", errors.New("private_key_path cannot be empty"))
|
||||
case c.PublicKeyPath == "":
|
||||
return wrapValidationError("jwt", errors.New("public_key_path cannot be empty"))
|
||||
default:
|
||||
return nil
|
||||
}
|
||||
}
|
||||
|
||||
func (c *JWT) loadConfig(v *viper.Viper) error {
|
||||
v.SetEnvPrefix("JWT")
|
||||
c.AccessTokenLifetime = v.GetDuration("ACCESS_TOKEN_LIFETIME")
|
||||
c.RefreshTokenLifetime = v.GetDuration("REFRESH_TOKEN_LIFETIME")
|
||||
c.PublicKeyPath = v.GetString("PUBLIC_KEY_PATH")
|
||||
c.PrivateKeyPath = v.GetString("PRIVATE_KEY_PATH")
|
||||
return nil
|
||||
}
|
||||
|
||||
func (c *JWT) copy() *JWT {
|
||||
return &JWT{
|
||||
AccessTokenLifetime: c.AccessTokenLifetime,
|
||||
RefreshTokenLifetime: c.RefreshTokenLifetime,
|
||||
PublicKeyPath: c.PublicKeyPath,
|
||||
PrivateKeyPath: c.PrivateKeyPath,
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,94 @@
|
||||
package config
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
|
||||
"github.com/spf13/viper"
|
||||
)
|
||||
|
||||
const (
|
||||
uri = "postgres://%s:%s@%s:%d/%s?sslmode=disable"
|
||||
)
|
||||
|
||||
type Postgres struct {
|
||||
Host string
|
||||
Port int
|
||||
User string
|
||||
Password string
|
||||
Database string
|
||||
VersionTable string
|
||||
RunMigrations bool
|
||||
MaxConnections int
|
||||
}
|
||||
|
||||
func (c *Postgres) Validate() error {
|
||||
switch {
|
||||
case c.Host == "":
|
||||
return wrapValidationError("postgres", errors.New("host cannot be empty"))
|
||||
case c.Port == 0:
|
||||
return wrapValidationError("postgres", errors.New("port cannot be empty"))
|
||||
case c.User == "":
|
||||
return wrapValidationError("postgres", errors.New("user cannot be empty"))
|
||||
case c.Password == "":
|
||||
return wrapValidationError("postgres", errors.New("password cannot be empty"))
|
||||
case c.Database == "":
|
||||
return wrapValidationError("postgres", errors.New("database cannot be empty"))
|
||||
case c.VersionTable == "":
|
||||
return wrapValidationError("postgres", errors.New("version_table name cannot be empty"))
|
||||
case c.MaxConnections == 0:
|
||||
return wrapValidationError("postgres", errors.New("max_connections cannot be empty"))
|
||||
default:
|
||||
return nil
|
||||
}
|
||||
}
|
||||
|
||||
func (c *Postgres) GetVersionTableName() string {
|
||||
if c == nil {
|
||||
return ""
|
||||
}
|
||||
return c.VersionTable
|
||||
}
|
||||
|
||||
func (c *Postgres) GetURI() string {
|
||||
if c == nil {
|
||||
return ""
|
||||
}
|
||||
return fmt.Sprintf(uri, c.User, c.Password, c.Host, c.Port, c.Database)
|
||||
}
|
||||
|
||||
func (c *Postgres) GetRunMigrations() bool {
|
||||
if c == nil {
|
||||
return false
|
||||
}
|
||||
return c.RunMigrations
|
||||
}
|
||||
|
||||
func (c *Postgres) loadConfig(v *viper.Viper) error {
|
||||
v.SetEnvPrefix("POSTGRES")
|
||||
c.Host = v.GetString("HOST")
|
||||
c.Port = v.GetInt("PORT")
|
||||
c.User = v.GetString("USER")
|
||||
c.Password = v.GetString("PASSWORD")
|
||||
c.Database = v.GetString("DATABASE")
|
||||
c.VersionTable = v.GetString("VERSION_TABLE")
|
||||
c.RunMigrations = v.GetBool("RUN_MIGRATIONS")
|
||||
c.MaxConnections = v.GetInt("MAX_CONNECTIONS")
|
||||
return nil
|
||||
}
|
||||
|
||||
func (c *Postgres) copy() *Postgres {
|
||||
if c == nil {
|
||||
return nil
|
||||
}
|
||||
return &Postgres{
|
||||
Host: c.Host,
|
||||
Port: c.Port,
|
||||
User: c.User,
|
||||
Password: c.Password,
|
||||
Database: c.Database,
|
||||
MaxConnections: c.MaxConnections,
|
||||
RunMigrations: c.RunMigrations,
|
||||
VersionTable: c.VersionTable,
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,72 @@
|
||||
package config
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"net"
|
||||
"time"
|
||||
|
||||
"github.com/redis/go-redis/v9"
|
||||
"github.com/spf13/viper"
|
||||
)
|
||||
|
||||
type Redis struct {
|
||||
Host string
|
||||
Port int
|
||||
Username string
|
||||
Password string
|
||||
DB int
|
||||
}
|
||||
|
||||
func (c *Redis) Validate() error {
|
||||
switch {
|
||||
case c.Host == "":
|
||||
return wrapValidationError("redis", errors.New("host cannot be empty"))
|
||||
case c.Port == 0:
|
||||
return wrapValidationError("redis", errors.New("port cannot be empty"))
|
||||
default:
|
||||
return nil
|
||||
}
|
||||
}
|
||||
|
||||
func (c *Redis) BuildRedisOptions() *redis.Options {
|
||||
if c == nil {
|
||||
return nil
|
||||
}
|
||||
return &redis.Options{
|
||||
Addr: net.JoinHostPort(c.Host, fmt.Sprintf("%d", c.Port)),
|
||||
Username: c.Username,
|
||||
Password: c.Password,
|
||||
DB: c.DB,
|
||||
DialTimeout: 200 * time.Millisecond,
|
||||
ReadTimeout: 200 * time.Millisecond,
|
||||
WriteTimeout: 200 * time.Millisecond,
|
||||
PoolTimeout: 200 * time.Millisecond,
|
||||
MaxRetries: -1,
|
||||
DialerRetries: 1,
|
||||
ContextTimeoutEnabled: true,
|
||||
}
|
||||
}
|
||||
|
||||
func (c *Redis) loadConfig(v *viper.Viper) error {
|
||||
v.SetEnvPrefix("REDIS")
|
||||
c.Host = v.GetString("HOST")
|
||||
c.Port = v.GetInt("PORT")
|
||||
c.DB = v.GetInt("DB")
|
||||
c.Password = v.GetString("PASSWORD")
|
||||
c.Username = v.GetString("USERNAME")
|
||||
return nil
|
||||
}
|
||||
|
||||
func (c *Redis) copy() *Redis {
|
||||
if c == nil {
|
||||
return nil
|
||||
}
|
||||
return &Redis{
|
||||
Host: c.Host,
|
||||
Port: c.Port,
|
||||
Username: c.Username,
|
||||
Password: c.Password,
|
||||
DB: c.DB,
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,69 @@
|
||||
package config
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"github.com/spf13/viper"
|
||||
)
|
||||
|
||||
type Server struct {
|
||||
Host string
|
||||
Port int
|
||||
ReadTimeout time.Duration
|
||||
WriteTimeout time.Duration
|
||||
IdleTimeout time.Duration
|
||||
ShutdownTimeout time.Duration
|
||||
Enabled bool
|
||||
}
|
||||
|
||||
func (c *Server) Validate() error {
|
||||
if !c.Enabled {
|
||||
return nil
|
||||
}
|
||||
switch {
|
||||
case c.Host == "":
|
||||
return wrapValidationError("server", errors.New("host cannot be empty"))
|
||||
case c.Port == 0:
|
||||
return wrapValidationError("server", errors.New("port cannot be empty"))
|
||||
case c.ReadTimeout == 0:
|
||||
return wrapValidationError("server", errors.New("read_timeout cannot be empty"))
|
||||
case c.WriteTimeout == 0:
|
||||
return wrapValidationError("server", errors.New("write_timeout cannot be empty"))
|
||||
case c.IdleTimeout == 0:
|
||||
return wrapValidationError("server", errors.New("idle_timeout cannot be empty"))
|
||||
case c.ShutdownTimeout == 0:
|
||||
return wrapValidationError("server", errors.New("shutdown_timeout name cannot be empty"))
|
||||
default:
|
||||
return nil
|
||||
}
|
||||
}
|
||||
|
||||
func (c *Server) loadConfig(v *viper.Viper) error {
|
||||
v.SetEnvPrefix("APP")
|
||||
c.Host = v.GetString("HOST")
|
||||
c.Port = v.GetInt("PORT")
|
||||
c.ReadTimeout = v.GetDuration("READ_TIMEOUT")
|
||||
c.WriteTimeout = v.GetDuration("WRITE_TIMEOUT")
|
||||
c.IdleTimeout = v.GetDuration("IDLE_TIMEOUT")
|
||||
c.ShutdownTimeout = v.GetDuration("SHUTDOWN_TIMEOUT")
|
||||
c.Enabled = v.GetBool("ENABLED")
|
||||
return c.Validate()
|
||||
}
|
||||
|
||||
func (c *Server) BindAddress() string {
|
||||
return fmt.Sprintf("%s:%d", c.Host, c.Port)
|
||||
}
|
||||
|
||||
func (c *Server) copy() *Server {
|
||||
return &Server{
|
||||
Host: c.Host,
|
||||
Port: c.Port,
|
||||
ReadTimeout: c.ReadTimeout,
|
||||
WriteTimeout: c.WriteTimeout,
|
||||
IdleTimeout: c.IdleTimeout,
|
||||
ShutdownTimeout: c.ShutdownTimeout,
|
||||
Enabled: c.Enabled,
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
package config
|
||||
|
||||
import "fmt"
|
||||
|
||||
func wrapValidationError(name string, err error) error {
|
||||
if err == nil {
|
||||
return nil
|
||||
}
|
||||
|
||||
return fmt.Errorf("%s validation error: %w", name, err)
|
||||
}
|
||||
@@ -0,0 +1,126 @@
|
||||
package dto
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"net/netip"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
|
||||
"gitea.privcloud.tech/mtusi2026/internal/pkg/types/role"
|
||||
)
|
||||
|
||||
// ---- Tokens ----
|
||||
|
||||
type UserDataInToken struct {
|
||||
TokenID uuid.UUID
|
||||
UserID uuid.UUID
|
||||
Role role.Role
|
||||
IsAccess bool
|
||||
|
||||
PhoneNumber *string
|
||||
Email *string
|
||||
|
||||
ExpiresAt time.Time
|
||||
IssuedAt time.Time
|
||||
}
|
||||
|
||||
func (u UserDataInToken) Validate() error {
|
||||
if u.TokenID == uuid.Nil {
|
||||
return errors.New("invalid token id")
|
||||
}
|
||||
if u.UserID == uuid.Nil {
|
||||
return errors.New("invalid user id")
|
||||
}
|
||||
if !u.Role.IsValid() {
|
||||
return errors.New("invalid role")
|
||||
}
|
||||
if u.ExpiresAt.IsZero() {
|
||||
return errors.New("invalid expiry")
|
||||
}
|
||||
if u.IssuedAt.IsZero() {
|
||||
return errors.New("invalid issued")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
type Token struct {
|
||||
Payload string
|
||||
}
|
||||
|
||||
type (
|
||||
AccessToken Token
|
||||
RefreshToken Token
|
||||
)
|
||||
|
||||
type Tokens struct {
|
||||
AccessToken AccessToken
|
||||
RefreshToken RefreshToken
|
||||
}
|
||||
|
||||
func (t AccessToken) Token() *Token {
|
||||
return new(Token(t))
|
||||
}
|
||||
|
||||
func (t RefreshToken) Token() *Token {
|
||||
return new(Token(t))
|
||||
}
|
||||
|
||||
type StoredRefreshToken struct {
|
||||
ID uuid.UUID
|
||||
UserID uuid.UUID
|
||||
TokenHash string
|
||||
UserAgent string
|
||||
IPAddress netip.Addr
|
||||
Role role.Role
|
||||
ExpiresAt time.Time
|
||||
RevokedAt *time.Time
|
||||
CreatedAt time.Time
|
||||
}
|
||||
|
||||
type RevokeRefreshToken struct {
|
||||
ID uuid.UUID
|
||||
RevokedAt time.Time
|
||||
}
|
||||
|
||||
type RevokeRefreshTokensByUserID struct {
|
||||
UserID uuid.UUID
|
||||
RevokedAt time.Time
|
||||
}
|
||||
|
||||
// ---- Auth ----
|
||||
|
||||
type Session struct {
|
||||
ExpiresAt time.Time
|
||||
Token string
|
||||
TokenType string
|
||||
User User
|
||||
}
|
||||
|
||||
type Login struct {
|
||||
Username string
|
||||
Password string
|
||||
}
|
||||
|
||||
type LoginResult struct {
|
||||
ExpiresAt time.Time
|
||||
TokenType string
|
||||
User User
|
||||
Tokens Tokens
|
||||
}
|
||||
|
||||
// UserCredentials is internal authentication data, never a public user response.
|
||||
type UserCredentials struct {
|
||||
User User
|
||||
PasswordHash string `json:"-"`
|
||||
}
|
||||
|
||||
type Logout struct {
|
||||
Token string
|
||||
}
|
||||
|
||||
type Register struct {
|
||||
Email string
|
||||
Password string
|
||||
RepeatPassword string
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
package dto
|
||||
|
||||
import (
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
)
|
||||
|
||||
type Chat struct {
|
||||
ID uuid.UUID
|
||||
Title string
|
||||
MemberIDs []uuid.UUID
|
||||
CreatedAt time.Time
|
||||
}
|
||||
|
||||
type CreateChat struct {
|
||||
CreatorID uuid.UUID
|
||||
Title string
|
||||
MemberIDs []uuid.UUID
|
||||
}
|
||||
|
||||
type ChatMember struct {
|
||||
UserID uuid.UUID
|
||||
ChatID uuid.UUID
|
||||
}
|
||||
|
||||
type ChatFilters struct {
|
||||
UserID uuid.UUID
|
||||
Limit *int
|
||||
AfterID *uuid.UUID
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
package dto
|
||||
|
||||
import (
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
)
|
||||
|
||||
type Message struct {
|
||||
ID uuid.UUID
|
||||
ChatID uuid.UUID
|
||||
SenderID uuid.UUID
|
||||
Text string
|
||||
CreatedAt time.Time
|
||||
}
|
||||
|
||||
type CreateMessage struct {
|
||||
ChatID uuid.UUID
|
||||
SenderID uuid.UUID
|
||||
Text string
|
||||
}
|
||||
|
||||
type MessageFilters struct {
|
||||
ChatID uuid.UUID
|
||||
UserID uuid.UUID
|
||||
Limit *int
|
||||
AfterID *uuid.UUID
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
package dto
|
||||
|
||||
import (
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
)
|
||||
|
||||
// Page is a page of records with the ID to use for the next page.
|
||||
type Page[T any] struct {
|
||||
Items []T
|
||||
NextCursorID *uuid.UUID
|
||||
}
|
||||
|
||||
// PagePosition is a resolved database cursor, ordered by creation time and ID.
|
||||
type PagePosition struct {
|
||||
CreatedAt time.Time
|
||||
ID uuid.UUID
|
||||
}
|
||||
|
||||
// PageQuery is prepared by a service; Limit includes the lookahead row.
|
||||
type PageQuery struct {
|
||||
Limit int
|
||||
After *PagePosition
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
package dto
|
||||
|
||||
import (
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
)
|
||||
|
||||
type User struct {
|
||||
ID uuid.UUID
|
||||
Username string
|
||||
DisplayName string
|
||||
CreatedAt time.Time
|
||||
}
|
||||
|
||||
type CreateUser struct {
|
||||
Username string
|
||||
DisplayName string
|
||||
Password string
|
||||
}
|
||||
|
||||
// CreateStoredUser contains the prepared database record, never a plaintext password.
|
||||
type CreateStoredUser struct {
|
||||
ID uuid.UUID
|
||||
Username string
|
||||
DisplayName string
|
||||
PasswordHash string `json:"-"`
|
||||
CreatedAt time.Time
|
||||
UpdatedAt time.Time
|
||||
}
|
||||
@@ -0,0 +1,137 @@
|
||||
// Package contracts provides primitives to interact with the openapi HTTP API.
|
||||
//
|
||||
// Code generated by github.com/oapi-codegen/oapi-codegen/v2 version v2.5.1 DO NOT EDIT.
|
||||
package contracts
|
||||
|
||||
import (
|
||||
"time"
|
||||
|
||||
openapi_types "github.com/oapi-codegen/runtime/types"
|
||||
)
|
||||
|
||||
const (
|
||||
BasicAuthScopes = "basicAuth.Scopes"
|
||||
BearerAuthScopes = "bearerAuth.Scopes"
|
||||
)
|
||||
|
||||
// Defines values for ErrorErrorCode.
|
||||
const (
|
||||
Conflict ErrorErrorCode = "conflict"
|
||||
InternalError ErrorErrorCode = "internal_error"
|
||||
InvalidRequest ErrorErrorCode = "invalid_request"
|
||||
NotFound ErrorErrorCode = "not_found"
|
||||
PayloadTooLarge ErrorErrorCode = "payload_too_large"
|
||||
RateLimited ErrorErrorCode = "rate_limited"
|
||||
Unauthorized ErrorErrorCode = "unauthorized"
|
||||
Unavailable ErrorErrorCode = "unavailable"
|
||||
UnsupportedMediaType ErrorErrorCode = "unsupported_media_type"
|
||||
)
|
||||
|
||||
// Defines values for HealthStatus.
|
||||
const (
|
||||
Ok HealthStatus = "ok"
|
||||
)
|
||||
|
||||
// Chat defines model for Chat.
|
||||
type Chat struct {
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
Id openapi_types.UUID `json:"id"`
|
||||
MemberIds []openapi_types.UUID `json:"member_ids"`
|
||||
Title string `json:"title"`
|
||||
}
|
||||
|
||||
// ChatPage defines model for ChatPage.
|
||||
type ChatPage struct {
|
||||
Items []Chat `json:"items"`
|
||||
NextCursor *string `json:"next_cursor"`
|
||||
}
|
||||
|
||||
// CreateChat defines model for CreateChat.
|
||||
type CreateChat struct {
|
||||
MemberIds []openapi_types.UUID `json:"member_ids"`
|
||||
Title string `json:"title"`
|
||||
}
|
||||
|
||||
// CreateMessage defines model for CreateMessage.
|
||||
type CreateMessage struct {
|
||||
Text string `json:"text"`
|
||||
}
|
||||
|
||||
// CreateUser defines model for CreateUser.
|
||||
type CreateUser struct {
|
||||
DisplayName string `json:"display_name"`
|
||||
Password *string `json:"password,omitempty"`
|
||||
Username string `json:"username"`
|
||||
}
|
||||
|
||||
// Error defines model for Error.
|
||||
type Error struct {
|
||||
Error struct {
|
||||
Code ErrorErrorCode `json:"code"`
|
||||
Message string `json:"message"`
|
||||
RequestId string `json:"request_id"`
|
||||
} `json:"error"`
|
||||
}
|
||||
|
||||
// ErrorErrorCode defines model for Error.Error.Code.
|
||||
type ErrorErrorCode string
|
||||
|
||||
// Health defines model for Health.
|
||||
type Health struct {
|
||||
Status HealthStatus `json:"status"`
|
||||
}
|
||||
|
||||
// HealthStatus defines model for Health.Status.
|
||||
type HealthStatus string
|
||||
|
||||
// Message defines model for Message.
|
||||
type Message struct {
|
||||
ChatId openapi_types.UUID `json:"chat_id"`
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
Id openapi_types.UUID `json:"id"`
|
||||
SenderId openapi_types.UUID `json:"sender_id"`
|
||||
Text string `json:"text"`
|
||||
}
|
||||
|
||||
// MessagePage defines model for MessagePage.
|
||||
type MessagePage struct {
|
||||
Items []Message `json:"items"`
|
||||
NextCursor *string `json:"next_cursor"`
|
||||
}
|
||||
|
||||
// Session defines model for Session.
|
||||
type Session struct {
|
||||
ExpiresAt time.Time `json:"expires_at"`
|
||||
Token string `json:"token"`
|
||||
TokenType string `json:"token_type"`
|
||||
User User `json:"user"`
|
||||
}
|
||||
|
||||
// User defines model for User.
|
||||
type User struct {
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
DisplayName string `json:"display_name"`
|
||||
Id openapi_types.UUID `json:"id"`
|
||||
Username string `json:"username"`
|
||||
}
|
||||
|
||||
// ListChatsParams defines parameters for ListChats.
|
||||
type ListChatsParams struct {
|
||||
Limit *int `form:"limit,omitempty" json:"limit,omitempty"`
|
||||
Cursor *string `form:"cursor,omitempty" json:"cursor,omitempty"`
|
||||
}
|
||||
|
||||
// ListMessagesParams defines parameters for ListMessages.
|
||||
type ListMessagesParams struct {
|
||||
Limit *int `form:"limit,omitempty" json:"limit,omitempty"`
|
||||
Cursor *string `form:"cursor,omitempty" json:"cursor,omitempty"`
|
||||
}
|
||||
|
||||
// CreateChatJSONRequestBody defines body for CreateChat for application/json ContentType.
|
||||
type CreateChatJSONRequestBody = CreateChat
|
||||
|
||||
// CreateMessageJSONRequestBody defines body for CreateMessage for application/json ContentType.
|
||||
type CreateMessageJSONRequestBody = CreateMessage
|
||||
|
||||
// RegisterUserJSONRequestBody defines body for RegisterUser for application/json ContentType.
|
||||
type RegisterUserJSONRequestBody = CreateUser
|
||||
@@ -0,0 +1,274 @@
|
||||
package apperr
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"net/http"
|
||||
|
||||
"github.com/jackc/pgerrcode"
|
||||
"github.com/jackc/pgx/v5"
|
||||
"github.com/jackc/pgx/v5/pgconn"
|
||||
grpcCodes "google.golang.org/grpc/codes"
|
||||
)
|
||||
|
||||
//go:generate stringer -type=Code -linecomment
|
||||
type Code uint16
|
||||
|
||||
const (
|
||||
// CodeBadRequest = {AppError: BAD_REQUEST, HTTP:400}
|
||||
CodeBadRequest Code = iota
|
||||
// CodePayloadTooLarge = {AppError: REQUEST_ENTITY_TOO_LARGE, HTTP:413}
|
||||
CodePayloadTooLarge
|
||||
// CodeValidation = {AppError: VALIDATION, HTTP:422}
|
||||
CodeValidation
|
||||
// CodeUnauthorized = {AppError: UNAUTHORIZED, HTTP:401}
|
||||
CodeUnauthorized
|
||||
// CodeForbidden = {AppError: FORBIDDEN, HTTP:403}
|
||||
CodeForbidden
|
||||
// CodeNotFound = {AppError: NOT_FOUND, HTTP:404}
|
||||
CodeNotFound
|
||||
// CodeAlreadyExists = {AppError: ALREADY_EXISTS, HTTP:409}
|
||||
CodeAlreadyExists
|
||||
// CodeConflict = {AppError: CONFLICT, HTTP:409}
|
||||
CodeConflict
|
||||
// CodeTooManyRequests = {AppError: TOO_MANY_REQUESTS, HTTP:429}
|
||||
CodeTooManyRequests
|
||||
// CodeTimeout = {AppError: TIMEOUT, HTTP:504}
|
||||
CodeTimeout
|
||||
// CodeInternal = {AppError: INTERNAL, HTTP:500}
|
||||
CodeInternal
|
||||
// CodeServiceUnavailable = {AppError: SERVICE_UNAVAILABLE, HTTP:503}
|
||||
CodeServiceUnavailable
|
||||
// CodeOK = {AppError: OK, HTTP:200}
|
||||
CodeOK
|
||||
// CodeLocked = {AppError: LOCKED, HTTP:423}
|
||||
CodeLocked
|
||||
// CodeUnsupportedMediaType = {AppError: UNSUPPORTED_MEDIA_TYPE, HTTP:415}
|
||||
CodeUnsupportedMediaType
|
||||
// CodeUnavailable = {AppError: SERVICE_UNAVAILABLE, HTTP: 503}
|
||||
CodeUnavailable
|
||||
)
|
||||
|
||||
func (c Code) HTTPStatus() int {
|
||||
if status, ok := httpStatusByCode[c]; ok {
|
||||
return status
|
||||
}
|
||||
return http.StatusInternalServerError
|
||||
}
|
||||
|
||||
func (c Code) GRPCCode() grpcCodes.Code {
|
||||
if code, ok := grpcCodeByCode[c]; ok {
|
||||
return code
|
||||
}
|
||||
return grpcCodes.Internal
|
||||
}
|
||||
|
||||
func (c Code) PostgresCodes() []string {
|
||||
codes := postgresCodesByCode[c]
|
||||
if len(codes) == 0 {
|
||||
return nil
|
||||
}
|
||||
|
||||
cp := make([]string, len(codes))
|
||||
copy(cp, codes)
|
||||
return cp
|
||||
}
|
||||
|
||||
func (c Code) PostgresCode() string {
|
||||
codes := c.PostgresCodes()
|
||||
if len(codes) == 0 {
|
||||
return ""
|
||||
}
|
||||
return codes[0]
|
||||
}
|
||||
|
||||
func CodeFromError(err error) Code {
|
||||
if err == nil {
|
||||
return CodeInternal
|
||||
}
|
||||
|
||||
var coded interface {
|
||||
Code() Code
|
||||
}
|
||||
if errors.As(err, &coded) {
|
||||
return coded.Code()
|
||||
}
|
||||
|
||||
if code, ok := codeFromRedisError(err, false, false); ok {
|
||||
return code
|
||||
}
|
||||
|
||||
return CodeFromPostgresError(err)
|
||||
}
|
||||
|
||||
func HTTPStatusFromError(err error) int {
|
||||
return CodeFromError(err).HTTPStatus()
|
||||
}
|
||||
|
||||
func GRPCCodeFromError(err error) grpcCodes.Code {
|
||||
return CodeFromError(err).GRPCCode()
|
||||
}
|
||||
|
||||
func CodeFromHTTPStatus(status int) Code {
|
||||
if code, ok := codeByHTTPStatus[status]; ok {
|
||||
return code
|
||||
}
|
||||
return CodeInternal
|
||||
}
|
||||
|
||||
func CodeFromGRPC(code grpcCodes.Code) Code {
|
||||
if appCode, ok := codeByGRPCCode[code]; ok {
|
||||
return appCode
|
||||
}
|
||||
return CodeInternal
|
||||
}
|
||||
|
||||
func CodeFromPostgres(pgCode string) Code {
|
||||
if code, ok := codeByPostgresCode[pgCode]; ok {
|
||||
return code
|
||||
}
|
||||
return CodeInternal
|
||||
}
|
||||
|
||||
func CodeFromPostgresError(err error) Code {
|
||||
if err == nil {
|
||||
return CodeInternal
|
||||
}
|
||||
|
||||
if code, ok := codeByPgxError[err]; ok {
|
||||
return code
|
||||
}
|
||||
|
||||
if pgErr, ok := errors.AsType[*pgconn.PgError](err); ok {
|
||||
return CodeFromPostgres(pgErr.Code)
|
||||
}
|
||||
|
||||
return CodeInternal
|
||||
}
|
||||
|
||||
var (
|
||||
httpStatusByCode = map[Code]int{
|
||||
CodeBadRequest: http.StatusBadRequest,
|
||||
CodeUnauthorized: http.StatusUnauthorized,
|
||||
CodeForbidden: http.StatusForbidden,
|
||||
CodeNotFound: http.StatusNotFound,
|
||||
CodeAlreadyExists: http.StatusConflict,
|
||||
CodeConflict: http.StatusConflict,
|
||||
CodePayloadTooLarge: http.StatusRequestEntityTooLarge,
|
||||
CodeTooManyRequests: http.StatusTooManyRequests,
|
||||
CodeValidation: http.StatusUnprocessableEntity,
|
||||
CodeTimeout: http.StatusGatewayTimeout,
|
||||
CodeInternal: http.StatusInternalServerError,
|
||||
CodeServiceUnavailable: http.StatusServiceUnavailable,
|
||||
CodeUnsupportedMediaType: http.StatusUnsupportedMediaType,
|
||||
CodeUnavailable: http.StatusServiceUnavailable,
|
||||
CodeOK: http.StatusOK,
|
||||
CodeLocked: http.StatusLocked,
|
||||
}
|
||||
codeByHTTPStatus = map[int]Code{
|
||||
http.StatusBadRequest: CodeBadRequest,
|
||||
http.StatusUnauthorized: CodeUnauthorized,
|
||||
http.StatusForbidden: CodeForbidden,
|
||||
http.StatusNotFound: CodeNotFound,
|
||||
http.StatusConflict: CodeConflict,
|
||||
http.StatusRequestEntityTooLarge: CodePayloadTooLarge,
|
||||
http.StatusTooManyRequests: CodeTooManyRequests,
|
||||
http.StatusUnprocessableEntity: CodeValidation,
|
||||
http.StatusGatewayTimeout: CodeTimeout,
|
||||
http.StatusInternalServerError: CodeInternal,
|
||||
http.StatusServiceUnavailable: CodeServiceUnavailable,
|
||||
http.StatusOK: CodeOK,
|
||||
http.StatusLocked: CodeLocked,
|
||||
http.StatusUnsupportedMediaType: CodeUnavailable,
|
||||
}
|
||||
grpcCodeByCode = map[Code]grpcCodes.Code{
|
||||
CodeBadRequest: grpcCodes.InvalidArgument,
|
||||
CodePayloadTooLarge: grpcCodes.ResourceExhausted,
|
||||
CodeValidation: grpcCodes.InvalidArgument,
|
||||
CodeUnauthorized: grpcCodes.Unauthenticated,
|
||||
CodeForbidden: grpcCodes.PermissionDenied,
|
||||
CodeNotFound: grpcCodes.NotFound,
|
||||
CodeAlreadyExists: grpcCodes.AlreadyExists,
|
||||
CodeConflict: grpcCodes.Aborted,
|
||||
CodeTooManyRequests: grpcCodes.ResourceExhausted,
|
||||
CodeTimeout: grpcCodes.DeadlineExceeded,
|
||||
CodeInternal: grpcCodes.Internal,
|
||||
CodeServiceUnavailable: grpcCodes.Unavailable,
|
||||
CodeOK: grpcCodes.OK,
|
||||
CodeLocked: grpcCodes.FailedPrecondition,
|
||||
}
|
||||
codeByGRPCCode = map[grpcCodes.Code]Code{
|
||||
grpcCodes.InvalidArgument: CodeBadRequest,
|
||||
grpcCodes.ResourceExhausted: CodeTooManyRequests,
|
||||
grpcCodes.Unauthenticated: CodeUnauthorized,
|
||||
grpcCodes.PermissionDenied: CodeForbidden,
|
||||
grpcCodes.NotFound: CodeNotFound,
|
||||
grpcCodes.AlreadyExists: CodeAlreadyExists,
|
||||
grpcCodes.Aborted: CodeConflict,
|
||||
grpcCodes.FailedPrecondition: CodeLocked,
|
||||
grpcCodes.DeadlineExceeded: CodeTimeout,
|
||||
grpcCodes.Internal: CodeInternal,
|
||||
grpcCodes.Unimplemented: CodeInternal,
|
||||
grpcCodes.Unavailable: CodeServiceUnavailable,
|
||||
grpcCodes.OK: CodeOK,
|
||||
}
|
||||
postgresCodesByCode = map[Code][]string{
|
||||
CodeBadRequest: {
|
||||
pgerrcode.InvalidTextRepresentation,
|
||||
pgerrcode.InvalidParameterValue,
|
||||
},
|
||||
CodeValidation: {
|
||||
pgerrcode.NotNullViolation,
|
||||
pgerrcode.CheckViolation,
|
||||
pgerrcode.StringDataRightTruncationDataException,
|
||||
pgerrcode.NumericValueOutOfRange,
|
||||
},
|
||||
CodeNotFound: {
|
||||
pgerrcode.ForeignKeyViolation,
|
||||
},
|
||||
CodeAlreadyExists: {
|
||||
pgerrcode.UniqueViolation,
|
||||
},
|
||||
CodeConflict: {
|
||||
pgerrcode.ExclusionViolation,
|
||||
pgerrcode.SerializationFailure,
|
||||
pgerrcode.DeadlockDetected,
|
||||
},
|
||||
CodeLocked: {
|
||||
pgerrcode.LockNotAvailable,
|
||||
pgerrcode.ObjectInUse,
|
||||
},
|
||||
CodeTooManyRequests: {
|
||||
pgerrcode.TooManyConnections,
|
||||
},
|
||||
CodeTimeout: {
|
||||
pgerrcode.QueryCanceled,
|
||||
},
|
||||
CodeInternal: {
|
||||
pgerrcode.ConnectionException,
|
||||
pgerrcode.ConnectionFailure,
|
||||
pgerrcode.SQLClientUnableToEstablishSQLConnection,
|
||||
pgerrcode.SQLServerRejectedEstablishmentOfSQLConnection,
|
||||
pgerrcode.TransactionResolutionUnknown,
|
||||
},
|
||||
CodeServiceUnavailable: {
|
||||
pgerrcode.CannotConnectNow,
|
||||
},
|
||||
}
|
||||
codeByPostgresCode = buildCodeByPostgresCode(postgresCodesByCode)
|
||||
codeByPgxError = map[error]Code{
|
||||
pgx.ErrNoRows: CodeNotFound,
|
||||
pgx.ErrTxClosed: CodeInternal,
|
||||
pgx.ErrTxCommitRollback: CodeConflict,
|
||||
pgx.ErrTooManyRows: CodeInternal,
|
||||
}
|
||||
)
|
||||
|
||||
func buildCodeByPostgresCode(src map[Code][]string) map[string]Code {
|
||||
dst := make(map[string]Code, len(src))
|
||||
for code, pgCodes := range src {
|
||||
for _, pgCode := range pgCodes {
|
||||
dst[pgCode] = code
|
||||
}
|
||||
}
|
||||
return dst
|
||||
}
|
||||
@@ -0,0 +1,37 @@
|
||||
// Code generated by "stringer -type=Code -linecomment"; DO NOT EDIT.
|
||||
|
||||
package apperr
|
||||
|
||||
import "strconv"
|
||||
|
||||
func _() {
|
||||
// An "invalid array index" compiler error signifies that the constant values have changed.
|
||||
// Re-run the stringer command to generate them again.
|
||||
var x [1]struct{}
|
||||
_ = x[CodeBadRequest-0]
|
||||
_ = x[CodePayloadTooLarge-1]
|
||||
_ = x[CodeValidation-2]
|
||||
_ = x[CodeUnauthorized-3]
|
||||
_ = x[CodeForbidden-4]
|
||||
_ = x[CodeNotFound-5]
|
||||
_ = x[CodeAlreadyExists-6]
|
||||
_ = x[CodeConflict-7]
|
||||
_ = x[CodeTooManyRequests-8]
|
||||
_ = x[CodeTimeout-9]
|
||||
_ = x[CodeInternal-10]
|
||||
_ = x[CodeServiceUnavailable-11]
|
||||
_ = x[CodeOK-12]
|
||||
_ = x[CodeLocked-13]
|
||||
}
|
||||
|
||||
const _Code_name = "CodeBadRequestCodePayloadTooLargeCodeValidationCodeUnauthorizedCodeForbiddenCodeNotFoundCodeAlreadyExistsCodeConflictCodeTooManyRequestsCodeTimeoutCodeInternalCodeServiceUnavailableCodeOKCodeLocked"
|
||||
|
||||
var _Code_index = [...]uint8{0, 14, 33, 47, 63, 76, 88, 105, 117, 136, 147, 159, 181, 187, 197}
|
||||
|
||||
func (i Code) String() string {
|
||||
idx := int(i) - 0
|
||||
if i < 0 || idx >= len(_Code_index)-1 {
|
||||
return "Code(" + strconv.FormatInt(int64(i), 10) + ")"
|
||||
}
|
||||
return _Code_name[_Code_index[idx]:_Code_index[idx+1]]
|
||||
}
|
||||
@@ -0,0 +1,123 @@
|
||||
package apperr
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
|
||||
grpcCodes "google.golang.org/grpc/codes"
|
||||
)
|
||||
|
||||
type AppError struct {
|
||||
err error
|
||||
msg string
|
||||
code Code
|
||||
meta metadata
|
||||
}
|
||||
|
||||
func New(code Code, msg string) error {
|
||||
return &AppError{
|
||||
msg: msg,
|
||||
code: code,
|
||||
meta: metadata{},
|
||||
}
|
||||
}
|
||||
|
||||
func Wrap(err error, code Code, msg string) error {
|
||||
m := AppError{
|
||||
err: err,
|
||||
msg: msg,
|
||||
code: code,
|
||||
meta: metadata{},
|
||||
}
|
||||
return &m
|
||||
}
|
||||
|
||||
func WrapAppError(err error, msg string) error {
|
||||
m := AppError{
|
||||
err: err,
|
||||
msg: msg,
|
||||
code: CodeInternal,
|
||||
meta: metadata{},
|
||||
}
|
||||
|
||||
if mistake := As(err); mistake != nil {
|
||||
m.err = mistake
|
||||
m.code = mistake.code
|
||||
m.meta = mistake.meta
|
||||
}
|
||||
|
||||
return &m
|
||||
}
|
||||
|
||||
func As(err error) *AppError {
|
||||
if mistakeErr, ok := errors.AsType[*AppError](err); ok {
|
||||
return mistakeErr
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func CodeIs(err error, code Code) bool {
|
||||
if appErr := As(err); appErr != nil && appErr.Code() == code {
|
||||
return true
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
func (e *AppError) Error() string {
|
||||
if e == nil {
|
||||
return ""
|
||||
}
|
||||
|
||||
if e.err == nil {
|
||||
if e.msg != "" {
|
||||
return e.msg
|
||||
}
|
||||
return e.code.String()
|
||||
}
|
||||
|
||||
if e.msg == "" {
|
||||
return e.err.Error()
|
||||
}
|
||||
|
||||
return fmt.Sprintf("%s: %s", e.msg, e.err.Error())
|
||||
}
|
||||
|
||||
func (e *AppError) Unwrap() error {
|
||||
if e == nil {
|
||||
return nil
|
||||
}
|
||||
return e.err
|
||||
}
|
||||
|
||||
func (e *AppError) Code() Code {
|
||||
if e == nil {
|
||||
return CodeInternal
|
||||
}
|
||||
return e.code
|
||||
}
|
||||
|
||||
func (e *AppError) Message() string {
|
||||
if e == nil {
|
||||
return ""
|
||||
}
|
||||
return e.msg
|
||||
}
|
||||
|
||||
func (e *AppError) Cause() error {
|
||||
if e == nil {
|
||||
return nil
|
||||
}
|
||||
return e.err
|
||||
}
|
||||
|
||||
func (e *AppError) Metadata() Metadata {
|
||||
return e.meta
|
||||
}
|
||||
|
||||
func (e *AppError) HTTPStatus() int {
|
||||
return e.Code().HTTPStatus()
|
||||
}
|
||||
|
||||
func (e *AppError) GRPCCode() grpcCodes.Code {
|
||||
return e.Code().GRPCCode()
|
||||
}
|
||||
@@ -0,0 +1,42 @@
|
||||
package apperr
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"maps"
|
||||
"strings"
|
||||
)
|
||||
|
||||
var _ Metadata = (*metadata)(nil)
|
||||
|
||||
type Metadata interface {
|
||||
Get(key metakey) string
|
||||
Clone() map[metakey]string
|
||||
CloneToAnyMap() map[string]any
|
||||
String() string
|
||||
}
|
||||
|
||||
type metadata map[metakey]string
|
||||
|
||||
func (m metadata) Get(key metakey) string {
|
||||
return m[key]
|
||||
}
|
||||
|
||||
func (m metadata) Clone() map[metakey]string {
|
||||
return maps.Clone(m)
|
||||
}
|
||||
|
||||
func (m metadata) CloneToAnyMap() map[string]any {
|
||||
newM := make(map[string]any, len(m))
|
||||
for k, v := range m {
|
||||
newM[k.String()] = v
|
||||
}
|
||||
return newM
|
||||
}
|
||||
|
||||
func (m metadata) String() string {
|
||||
var b strings.Builder
|
||||
for k, v := range m {
|
||||
b.WriteString(fmt.Sprintf("%s: %s, ", k, v))
|
||||
}
|
||||
return b.String()
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
package apperr
|
||||
|
||||
type metakey uint16
|
||||
|
||||
const (
|
||||
PgErrorCode metakey = iota
|
||||
RedisErrorCode
|
||||
)
|
||||
|
||||
func (m metakey) String() string {
|
||||
switch m {
|
||||
case PgErrorCode:
|
||||
return "pg_err_code"
|
||||
case RedisErrorCode:
|
||||
return "redis_err_code"
|
||||
default:
|
||||
return "unknown"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,63 @@
|
||||
package apperr
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
|
||||
"github.com/jackc/pgx/v5"
|
||||
"github.com/jackc/pgx/v5/pgconn"
|
||||
)
|
||||
|
||||
func WrapPostgres(err error, msg string) error {
|
||||
m := AppError{
|
||||
err: err,
|
||||
msg: msg,
|
||||
code: CodeInternal,
|
||||
meta: metadata{},
|
||||
}
|
||||
|
||||
m.handlePostgres()
|
||||
|
||||
return &m
|
||||
}
|
||||
|
||||
func (e *AppError) handlePostgres() {
|
||||
if e.err == nil {
|
||||
e.code = CodeOK
|
||||
return
|
||||
}
|
||||
|
||||
if pgErr, ok := errors.AsType[*pgconn.PgError](e.err); ok {
|
||||
e.meta[PgErrorCode] = pgErr.Code
|
||||
e.code = CodeFromPostgres(pgErr.Code)
|
||||
return
|
||||
}
|
||||
switch {
|
||||
case errors.Is(e.err, pgx.ErrNoRows):
|
||||
e.msg = fmt.Sprintf("not found: %s", e.msg)
|
||||
e.code = CodeNotFound
|
||||
return
|
||||
case errors.Is(e.err, pgx.ErrTooManyRows):
|
||||
e.msg = fmt.Sprintf("got too many rows: %s", e.msg)
|
||||
e.code = CodeInternal
|
||||
return
|
||||
case errors.Is(e.err, pgx.ErrTxClosed):
|
||||
e.msg = fmt.Sprintf("transaction is closed: %s", e.msg)
|
||||
e.code = CodeInternal
|
||||
return
|
||||
case errors.Is(e.err, pgx.ErrTxCommitRollback):
|
||||
e.msg = fmt.Sprintf("transaction commit resulted in rollback: %s", e.msg)
|
||||
e.code = CodeInternal
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
func (e *AppError) PgCode() string {
|
||||
if e == nil {
|
||||
return ""
|
||||
}
|
||||
if e.meta == nil {
|
||||
return ""
|
||||
}
|
||||
return e.meta.Get(PgErrorCode)
|
||||
}
|
||||
@@ -0,0 +1,170 @@
|
||||
package apperr
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"net"
|
||||
"strings"
|
||||
|
||||
"github.com/redis/go-redis/v9"
|
||||
)
|
||||
|
||||
func WrapRedis(err error, msg string) error {
|
||||
m := AppError{
|
||||
err: err,
|
||||
msg: msg,
|
||||
meta: metadata{},
|
||||
}
|
||||
|
||||
m.handleRedis()
|
||||
|
||||
return &m
|
||||
}
|
||||
|
||||
func CodeFromRedisError(err error) Code {
|
||||
code, ok := codeFromRedisError(err, true, true)
|
||||
if !ok {
|
||||
return CodeInternal
|
||||
}
|
||||
return code
|
||||
}
|
||||
|
||||
func (e *AppError) handleRedis() {
|
||||
if e.err == nil {
|
||||
e.code = CodeOK
|
||||
return
|
||||
}
|
||||
|
||||
if code := redisErrorCode(e.err); code != "" {
|
||||
e.meta[RedisErrorCode] = code
|
||||
}
|
||||
|
||||
if errors.Is(e.err, redis.Nil) {
|
||||
e.msg = fmt.Sprintf("not found: %s", e.msg)
|
||||
}
|
||||
|
||||
e.code = CodeFromRedisError(e.err)
|
||||
}
|
||||
|
||||
func (e *AppError) RedisCode() string {
|
||||
if e == nil {
|
||||
return ""
|
||||
}
|
||||
if e.meta == nil {
|
||||
return ""
|
||||
}
|
||||
return e.meta.Get(RedisErrorCode)
|
||||
}
|
||||
|
||||
func codeFromRedisError(err error, includeTransport bool, includeProtocolString bool) (Code, bool) {
|
||||
if err == nil {
|
||||
return CodeInternal, false
|
||||
}
|
||||
|
||||
switch {
|
||||
case errors.Is(err, redis.Nil):
|
||||
return CodeNotFound, true
|
||||
case errors.Is(err, redis.TxFailedErr):
|
||||
return CodeConflict, true
|
||||
case errors.Is(err, redis.ErrCrossSlot):
|
||||
return CodeBadRequest, true
|
||||
case errors.Is(err, redis.ErrPoolTimeout):
|
||||
return CodeTimeout, true
|
||||
case errors.Is(err, redis.ErrPoolExhausted):
|
||||
return CodeTooManyRequests, true
|
||||
case errors.Is(err, redis.ErrClosed):
|
||||
return CodeServiceUnavailable, true
|
||||
}
|
||||
|
||||
if includeTransport {
|
||||
if errors.Is(err, context.Canceled) ||
|
||||
errors.Is(err, context.DeadlineExceeded) {
|
||||
return CodeTimeout, true
|
||||
}
|
||||
|
||||
if netErr, ok := errors.AsType[net.Error](err); ok {
|
||||
if netErr.Timeout() {
|
||||
return CodeTimeout, true
|
||||
}
|
||||
return CodeServiceUnavailable, true
|
||||
}
|
||||
}
|
||||
|
||||
hasRedisError := isRedisError(err)
|
||||
if !hasRedisError && !includeProtocolString {
|
||||
return CodeInternal, false
|
||||
}
|
||||
|
||||
switch {
|
||||
case redis.IsExecAbortError(err):
|
||||
return CodeConflict, true
|
||||
case redis.IsMaxClientsError(err):
|
||||
return CodeTooManyRequests, true
|
||||
case redis.IsLoadingError(err),
|
||||
redis.IsReadOnlyError(err),
|
||||
redis.IsClusterDownError(err),
|
||||
redis.IsTryAgainError(err),
|
||||
redis.IsMasterDownError(err),
|
||||
redis.IsNoReplicasError(err),
|
||||
redis.IsOOMError(err):
|
||||
return CodeServiceUnavailable, true
|
||||
case redis.IsAuthError(err),
|
||||
redis.IsPermissionError(err):
|
||||
return CodeInternal, true
|
||||
}
|
||||
|
||||
if _, ok := redis.IsMovedError(err); ok {
|
||||
return CodeServiceUnavailable, true
|
||||
}
|
||||
if _, ok := redis.IsAskError(err); ok {
|
||||
return CodeServiceUnavailable, true
|
||||
}
|
||||
|
||||
if hasRedisError {
|
||||
return CodeInternal, true
|
||||
}
|
||||
|
||||
return CodeInternal, false
|
||||
}
|
||||
|
||||
func isRedisError(err error) bool {
|
||||
if err == nil {
|
||||
return false
|
||||
}
|
||||
|
||||
var redisErr redis.Error
|
||||
return errors.As(err, &redisErr)
|
||||
}
|
||||
|
||||
func redisErrorCode(err error) string {
|
||||
switch {
|
||||
case err == nil:
|
||||
return ""
|
||||
case errors.Is(err, redis.Nil):
|
||||
return "nil"
|
||||
case errors.Is(err, redis.TxFailedErr):
|
||||
return "tx_failed"
|
||||
case errors.Is(err, redis.ErrCrossSlot):
|
||||
return "CROSSSLOT"
|
||||
case errors.Is(err, redis.ErrPoolTimeout):
|
||||
return "pool_timeout"
|
||||
case errors.Is(err, redis.ErrPoolExhausted):
|
||||
return "pool_exhausted"
|
||||
case errors.Is(err, redis.ErrClosed):
|
||||
return "closed"
|
||||
}
|
||||
|
||||
var redisErr redis.Error
|
||||
if !errors.As(err, &redisErr) {
|
||||
return ""
|
||||
}
|
||||
|
||||
msg := strings.TrimSpace(redisErr.Error())
|
||||
msg = strings.TrimPrefix(msg, "ERR ")
|
||||
parts := strings.Fields(msg)
|
||||
if len(parts) == 0 {
|
||||
return ""
|
||||
}
|
||||
return parts[0]
|
||||
}
|
||||
@@ -0,0 +1,144 @@
|
||||
package jwtprovider
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"log/slog"
|
||||
"time"
|
||||
|
||||
"github.com/golang-jwt/jwt/v5"
|
||||
"github.com/google/uuid"
|
||||
|
||||
"gitea.privcloud.tech/mtusi2026/internal/dto"
|
||||
"gitea.privcloud.tech/mtusi2026/internal/pkg/types/role"
|
||||
)
|
||||
|
||||
var _ Claims = (*jwtClaims)(nil)
|
||||
|
||||
type Claims interface {
|
||||
GetTopTokenID() (uuid.UUID, bool)
|
||||
GetTopUserID() (uuid.UUID, bool)
|
||||
GetTopRole() (role.Role, bool)
|
||||
GetTopIsAccess() (bool, bool)
|
||||
GetTopExpiresAt() (time.Time, bool)
|
||||
GetTopIssuedAt() (time.Time, bool)
|
||||
}
|
||||
|
||||
type claimsParseFunc func(token *dto.Token) (*jwtClaims, error)
|
||||
|
||||
type jwtClaims struct {
|
||||
jwt.RegisteredClaims
|
||||
|
||||
IsAccess bool `json:"is_access"`
|
||||
Role role.Role `json:"role"`
|
||||
}
|
||||
|
||||
func (claims *jwtClaims) GetTopTokenID() (uuid.UUID, bool) {
|
||||
parsed, err := uuid.Parse(claims.ID)
|
||||
if err != nil {
|
||||
return uuid.Nil, false
|
||||
}
|
||||
return parsed, true
|
||||
}
|
||||
|
||||
func (claims *jwtClaims) GetTopUserID() (uuid.UUID, bool) {
|
||||
parsed, err := uuid.Parse(claims.Subject)
|
||||
if err != nil {
|
||||
return uuid.Nil, false
|
||||
}
|
||||
return parsed, true
|
||||
}
|
||||
|
||||
func (claims *jwtClaims) GetTopRole() (role.Role, bool) {
|
||||
return claims.Role, true
|
||||
}
|
||||
|
||||
func (claims *jwtClaims) GetTopIsAccess() (bool, bool) {
|
||||
return claims.IsAccess, true
|
||||
}
|
||||
|
||||
func (claims *jwtClaims) GetTopExpiresAt() (time.Time, bool) {
|
||||
if claims.ExpiresAt == nil {
|
||||
return time.Time{}, false
|
||||
}
|
||||
return claims.ExpiresAt.Time, true
|
||||
}
|
||||
|
||||
func (claims *jwtClaims) GetTopIssuedAt() (time.Time, bool) {
|
||||
if claims.IssuedAt == nil {
|
||||
return time.Time{}, false
|
||||
}
|
||||
return claims.IssuedAt.Time, true
|
||||
}
|
||||
|
||||
func (claims *jwtClaims) userData() (*dto.UserDataInToken, error) {
|
||||
var u dto.UserDataInToken
|
||||
|
||||
tokenID, err := uuid.Parse(claims.ID)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to parse token id: %w", err)
|
||||
}
|
||||
u.TokenID = tokenID
|
||||
|
||||
userID, err := uuid.Parse(claims.Subject)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to parse user id from token %q: %w", claims.Subject, err)
|
||||
}
|
||||
u.UserID = userID
|
||||
|
||||
u.Role = claims.Role
|
||||
u.IsAccess = claims.IsAccess
|
||||
|
||||
if claims.ExpiresAt != nil {
|
||||
u.ExpiresAt = claims.ExpiresAt.Time
|
||||
}
|
||||
|
||||
if claims.IssuedAt != nil {
|
||||
u.IssuedAt = claims.IssuedAt.Time
|
||||
}
|
||||
|
||||
return &u, nil
|
||||
}
|
||||
|
||||
func (p *provider) parseClaimsFromProtectedJWT(token *dto.Token) (*jwtClaims, error) {
|
||||
if token == nil {
|
||||
return nil, ErrTokenIsMissing
|
||||
}
|
||||
|
||||
claims := &jwtClaims{}
|
||||
|
||||
parsed, err := jwt.ParseWithClaims(
|
||||
token.Payload,
|
||||
claims,
|
||||
p.readKeyFunc,
|
||||
jwt.WithValidMethods([]string{jwt.SigningMethodRS256.Alg()}),
|
||||
jwt.WithExpirationRequired(),
|
||||
jwt.WithIssuedAt(),
|
||||
)
|
||||
if err != nil {
|
||||
slog.Error("failed to parse token with claims", "error", err)
|
||||
return nil, ErrInvalidToken
|
||||
}
|
||||
|
||||
if !parsed.Valid {
|
||||
slog.Error("failed to parse token: provided invalid token", "valid", parsed.Valid)
|
||||
return nil, ErrInvalidToken
|
||||
}
|
||||
|
||||
return claims, nil
|
||||
}
|
||||
|
||||
func (p *provider) parseClaimsFromExposedJWT(token *dto.Token) (*jwtClaims, error) {
|
||||
if token == nil {
|
||||
return nil, ErrTokenIsMissing
|
||||
}
|
||||
|
||||
claims := &jwtClaims{}
|
||||
|
||||
_, _, err := new(jwt.Parser).ParseUnverified(token.Payload, claims)
|
||||
if err != nil {
|
||||
slog.Error("failed to parse token: provided invalid token")
|
||||
return nil, ErrInvalidToken
|
||||
}
|
||||
|
||||
return claims, nil
|
||||
}
|
||||
@@ -0,0 +1,84 @@
|
||||
package jwtprovider
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
)
|
||||
|
||||
const (
|
||||
accessTokenCookieKey = "auth-access-token"
|
||||
refreshTokenCookieKey = "auth-refresh-token"
|
||||
expiresAtCookieKey = "auth-exp"
|
||||
)
|
||||
|
||||
type CookieBuilderFabric struct {
|
||||
fabric func() http.Cookie
|
||||
}
|
||||
|
||||
func newCookieBuilder(
|
||||
domain string,
|
||||
path string,
|
||||
secure bool,
|
||||
sameSite http.SameSite,
|
||||
) *CookieBuilderFabric {
|
||||
return &CookieBuilderFabric{
|
||||
fabric: newCookieFabric(domain, path, secure, sameSite),
|
||||
}
|
||||
}
|
||||
|
||||
func (b *CookieBuilderFabric) Builder() *CookieBuilder {
|
||||
return &CookieBuilder{
|
||||
cookie: b.fabric(),
|
||||
}
|
||||
}
|
||||
|
||||
func newCookieFabric(
|
||||
_ string,
|
||||
path string,
|
||||
secure bool,
|
||||
sameSite http.SameSite) func() http.Cookie {
|
||||
return func() http.Cookie {
|
||||
return http.Cookie{
|
||||
Path: path,
|
||||
Secure: secure,
|
||||
SameSite: sameSite,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
type CookieBuilder struct {
|
||||
cookie http.Cookie
|
||||
}
|
||||
|
||||
func (b *CookieBuilder) AccessName() *CookieBuilder {
|
||||
b.cookie.Name = accessTokenCookieKey
|
||||
return b
|
||||
}
|
||||
|
||||
func (b *CookieBuilder) ExpiresName() *CookieBuilder {
|
||||
b.cookie.Name = expiresAtCookieKey
|
||||
return b
|
||||
}
|
||||
|
||||
func (b *CookieBuilder) RefreshName() *CookieBuilder {
|
||||
b.cookie.Name = refreshTokenCookieKey
|
||||
return b
|
||||
}
|
||||
|
||||
func (b *CookieBuilder) Value(value string) *CookieBuilder {
|
||||
b.cookie.Value = value
|
||||
return b
|
||||
}
|
||||
|
||||
func (b *CookieBuilder) HTTPOnly() *CookieBuilder {
|
||||
b.cookie.HttpOnly = true
|
||||
return b
|
||||
}
|
||||
|
||||
func (b *CookieBuilder) MaxAge(maxAge int) *CookieBuilder {
|
||||
b.cookie.MaxAge = maxAge
|
||||
return b
|
||||
}
|
||||
|
||||
func (b *CookieBuilder) Build() *http.Cookie {
|
||||
return new(b.cookie)
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
package jwtprovider
|
||||
|
||||
import (
|
||||
"errors"
|
||||
)
|
||||
|
||||
var (
|
||||
ErrDecode = errors.New("failed to decode argument")
|
||||
ErrNotFound = errors.New("not found")
|
||||
ErrUnexpectedAlgorithm = errors.New("unexpected signing algorithm")
|
||||
ErrTokenIsMissing = errors.New("token is missing")
|
||||
ErrInvalidToken = errors.New("provided invalid token")
|
||||
ErrInvalidUserDataInToken = errors.New("invalid user data in token")
|
||||
ErrInvalidTokenClaims = errors.New("provided invalid token claims")
|
||||
ErrInvalidBirthDateFormat = errors.New("provided invalid birth date format")
|
||||
ErrTokenExpired = errors.New("token is expired")
|
||||
ErrFailedToSign = errors.New("failed to sign jwt")
|
||||
)
|
||||
@@ -0,0 +1,26 @@
|
||||
package jwtprovider
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
|
||||
"github.com/google/uuid"
|
||||
|
||||
"gitea.privcloud.tech/mtusi2026/internal/dto"
|
||||
"gitea.privcloud.tech/mtusi2026/internal/pkg/types/role"
|
||||
)
|
||||
|
||||
type Provider interface {
|
||||
Parse(token *dto.Token) (*dto.UserDataInToken, error)
|
||||
CreateRefreshAndAccessTokensForUser(userID uuid.UUID, role role.Role) (*dto.Tokens, error)
|
||||
ParseVerified(token *dto.Token) (*dto.UserDataInToken, error)
|
||||
ParseUnverified(token *dto.Token) (*dto.UserDataInToken, error)
|
||||
ValidateUserDataInToken(u *dto.UserDataInToken) error
|
||||
}
|
||||
|
||||
type Cookie interface {
|
||||
Enabled() bool
|
||||
Set(w http.ResponseWriter, tokens *dto.Tokens)
|
||||
Clear(w http.ResponseWriter)
|
||||
AccessToken(r *http.Request) *dto.AccessToken
|
||||
RefreshToken(r *http.Request) *dto.RefreshToken
|
||||
}
|
||||
@@ -0,0 +1,199 @@
|
||||
package jwtprovider
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"net/http"
|
||||
"strconv"
|
||||
"time"
|
||||
|
||||
"gitea.privcloud.tech/mtusi2026/internal/config"
|
||||
"gitea.privcloud.tech/mtusi2026/internal/dto"
|
||||
)
|
||||
|
||||
type manager struct {
|
||||
enabled bool
|
||||
cookieFabric *CookieBuilderFabric
|
||||
prv Provider
|
||||
}
|
||||
|
||||
func NewCookieManager(cfg *config.Config, provider Provider) Cookie {
|
||||
m := &manager{
|
||||
//enabled: cfg.Cookies.Enabled,
|
||||
//cookieFabric: newCookieBuilder(
|
||||
// cfg.Cookies.Domain,
|
||||
// cfg.Cookies.Path,
|
||||
// cfg.Cookies.Secure,
|
||||
// cfg.Cookies.SameSite,
|
||||
//),
|
||||
prv: provider,
|
||||
}
|
||||
|
||||
if !m.enabled {
|
||||
return m
|
||||
}
|
||||
|
||||
if err := m.cookieFabric.
|
||||
Builder().
|
||||
AccessName().
|
||||
Value("test").
|
||||
HTTPOnly().
|
||||
MaxAge(0).
|
||||
Build().
|
||||
Valid(); err != nil {
|
||||
panic(fmt.Errorf("cookie validation failed: %w", err))
|
||||
}
|
||||
|
||||
return m
|
||||
}
|
||||
|
||||
func (m *manager) Enabled() bool {
|
||||
return m.enabled
|
||||
}
|
||||
|
||||
func (m *manager) Set(w http.ResponseWriter, tokens *dto.Tokens) {
|
||||
if !m.enabled || tokens == nil {
|
||||
return
|
||||
}
|
||||
|
||||
if tokens.AccessToken.Payload != "" {
|
||||
m.setAccess(tokens.AccessToken, w)
|
||||
}
|
||||
|
||||
if tokens.RefreshToken.Payload != "" {
|
||||
m.setRefresh(tokens.RefreshToken, w)
|
||||
}
|
||||
}
|
||||
|
||||
func (m *manager) Clear(w http.ResponseWriter) {
|
||||
if !m.enabled {
|
||||
return
|
||||
}
|
||||
|
||||
for _, name := range []string{accessTokenCookieKey, refreshTokenCookieKey, expiresAtCookieKey} {
|
||||
b := m.cookieFabric.
|
||||
Builder().
|
||||
MaxAge(-1)
|
||||
|
||||
switch name {
|
||||
case expiresAtCookieKey:
|
||||
b.ExpiresName()
|
||||
case refreshTokenCookieKey:
|
||||
b.RefreshName().
|
||||
HTTPOnly()
|
||||
case accessTokenCookieKey:
|
||||
b.AccessName().
|
||||
HTTPOnly()
|
||||
}
|
||||
http.SetCookie(w, b.Build())
|
||||
}
|
||||
}
|
||||
|
||||
func (m *manager) AccessToken(r *http.Request) *dto.AccessToken {
|
||||
if !m.enabled {
|
||||
return nil
|
||||
}
|
||||
|
||||
c, err := r.Cookie(accessTokenCookieKey)
|
||||
if err != nil {
|
||||
return nil
|
||||
}
|
||||
|
||||
return &dto.AccessToken{
|
||||
Payload: c.Value,
|
||||
}
|
||||
}
|
||||
|
||||
func (m *manager) RefreshToken(r *http.Request) *dto.RefreshToken {
|
||||
if !m.enabled {
|
||||
return nil
|
||||
}
|
||||
|
||||
c, err := r.Cookie(refreshTokenCookieKey)
|
||||
if err != nil {
|
||||
return nil
|
||||
}
|
||||
|
||||
return &dto.RefreshToken{
|
||||
Payload: c.Value,
|
||||
}
|
||||
}
|
||||
|
||||
func (m *manager) setAccess(token dto.AccessToken, w http.ResponseWriter) {
|
||||
accessTTL := m.tokenTTL(token.Token())
|
||||
if accessTTL < 0 {
|
||||
http.SetCookie(w, m.cookieFabric.
|
||||
Builder().
|
||||
AccessName().
|
||||
HTTPOnly().
|
||||
MaxAge(-1).
|
||||
Build(),
|
||||
)
|
||||
http.SetCookie(w, m.cookieFabric.
|
||||
Builder().
|
||||
ExpiresName().
|
||||
MaxAge(-1).
|
||||
Build(),
|
||||
)
|
||||
} else if tokenExpiresAt := m.tokenExpiry(token.Token()); !tokenExpiresAt.IsZero() {
|
||||
http.SetCookie(w, m.cookieFabric.
|
||||
Builder().
|
||||
AccessName().
|
||||
Value(token.Payload).
|
||||
HTTPOnly().
|
||||
MaxAge(accessTTL).
|
||||
Build(),
|
||||
)
|
||||
http.SetCookie(w, m.cookieFabric.
|
||||
Builder().
|
||||
ExpiresName().
|
||||
Value(strconv.FormatInt(tokenExpiresAt.Unix(), 10)).
|
||||
MaxAge(accessTTL).
|
||||
Build(),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
func (m *manager) setRefresh(token dto.RefreshToken, w http.ResponseWriter) {
|
||||
refreshTTL := m.tokenTTL(token.Token())
|
||||
if refreshTTL < 0 {
|
||||
http.SetCookie(w, m.cookieFabric.
|
||||
Builder().
|
||||
RefreshName().
|
||||
HTTPOnly().
|
||||
MaxAge(-1).
|
||||
Build(),
|
||||
)
|
||||
} else {
|
||||
http.SetCookie(w, m.cookieFabric.
|
||||
Builder().
|
||||
RefreshName().
|
||||
Value(token.Payload).
|
||||
HTTPOnly().
|
||||
MaxAge(refreshTTL).
|
||||
Build(),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
func (m *manager) tokenTTL(token *dto.Token) int {
|
||||
expiresAt := m.tokenExpiry(token)
|
||||
|
||||
if expiresAt.IsZero() {
|
||||
return -1
|
||||
}
|
||||
|
||||
ttl := int(time.Until(expiresAt).Seconds())
|
||||
if ttl <= 0 {
|
||||
return -1
|
||||
}
|
||||
|
||||
return ttl
|
||||
}
|
||||
|
||||
func (m *manager) tokenExpiry(token *dto.Token) time.Time {
|
||||
data, err := m.prv.ParseUnverified(token)
|
||||
if err != nil {
|
||||
return time.Time{}
|
||||
}
|
||||
return data.ExpiresAt
|
||||
}
|
||||
@@ -0,0 +1,180 @@
|
||||
package jwtprovider
|
||||
|
||||
import (
|
||||
"crypto/rsa"
|
||||
"fmt"
|
||||
"log/slog"
|
||||
"time"
|
||||
|
||||
"github.com/golang-jwt/jwt/v5"
|
||||
"github.com/google/uuid"
|
||||
|
||||
"gitea.privcloud.tech/mtusi2026/internal/config"
|
||||
"gitea.privcloud.tech/mtusi2026/internal/dto"
|
||||
"gitea.privcloud.tech/mtusi2026/internal/pkg/types/environment"
|
||||
"gitea.privcloud.tech/mtusi2026/internal/pkg/types/role"
|
||||
)
|
||||
|
||||
var (
|
||||
_ Provider = (*provider)(nil)
|
||||
)
|
||||
|
||||
type provider struct {
|
||||
accessLifetime time.Duration
|
||||
refreshLifetime time.Duration
|
||||
publicKey *rsa.PublicKey
|
||||
privateKey *rsa.PrivateKey
|
||||
parseFunc claimsParseFunc
|
||||
}
|
||||
|
||||
func New(cfg *config.Config) Provider {
|
||||
p := provider{
|
||||
accessLifetime: cfg.JWT.AccessTokenLifetime,
|
||||
refreshLifetime: cfg.JWT.RefreshTokenLifetime,
|
||||
}
|
||||
p.parseFunc = p.parseClaimsFromProtectedJWT
|
||||
|
||||
if cfg.Application.Environment == environment.ApplicationEnvironmentDev {
|
||||
p.parseFunc = p.parseClaimsFromExposedJWT
|
||||
}
|
||||
|
||||
var err error
|
||||
if p.publicKey, err = readPublicKeyFromFile(cfg.JWT.PublicKeyPath); err != nil {
|
||||
slog.Error("failed to read public key", "error", err)
|
||||
panic(fmt.Errorf("failed to read public key: %w", err))
|
||||
}
|
||||
if p.privateKey, err = readPrivateKeyFromFile(cfg.JWT.PrivateKeyPath); err != nil {
|
||||
slog.Error("failed to read private key", "error", err)
|
||||
panic(fmt.Errorf("failed to read private key: %w", err))
|
||||
}
|
||||
|
||||
return &p
|
||||
}
|
||||
|
||||
func (p *provider) Parse(token *dto.Token) (*dto.UserDataInToken, error) {
|
||||
claims, err := p.parseFunc(token)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return claims.userData()
|
||||
}
|
||||
|
||||
func (p *provider) ParseUnverified(t *dto.Token) (*dto.UserDataInToken, error) {
|
||||
if t == nil {
|
||||
return nil, ErrTokenIsMissing
|
||||
}
|
||||
|
||||
claims, err := p.parseClaimsFromExposedJWT(t)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return claims.userData()
|
||||
}
|
||||
|
||||
func (p *provider) ParseVerified(t *dto.Token) (*dto.UserDataInToken, error) {
|
||||
if t == nil {
|
||||
return nil, ErrTokenIsMissing
|
||||
}
|
||||
claims, err := p.parseClaimsFromProtectedJWT(t)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to parse token: %w", err)
|
||||
}
|
||||
|
||||
return claims.userData()
|
||||
}
|
||||
|
||||
func (p *provider) CreateAccessTokenForUser(userID uuid.UUID, role role.Role) (*dto.AccessToken, error) {
|
||||
t, err := p.createTokenForUser(userID, true, role)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &dto.AccessToken{
|
||||
Payload: t.Payload,
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (p *provider) CreateRefreshTokenForUser(userID uuid.UUID, role role.Role) (*dto.RefreshToken, error) {
|
||||
t, err := p.createTokenForUser(userID, false, role)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &dto.RefreshToken{
|
||||
Payload: t.Payload,
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (p *provider) CreateRefreshAndAccessTokensForUser(userID uuid.UUID, role role.Role) (*dto.Tokens, error) {
|
||||
access, err := p.CreateAccessTokenForUser(userID, role)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
refresh, err := p.CreateRefreshTokenForUser(userID, role)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &dto.Tokens{
|
||||
AccessToken: *access,
|
||||
RefreshToken: *refresh,
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (p *provider) createTokenForUser(userID uuid.UUID, isAccess bool, role role.Role) (*dto.Token, error) {
|
||||
now := time.Now()
|
||||
var tokenExpiresAt time.Time
|
||||
if isAccess {
|
||||
tokenExpiresAt = now.Add(p.accessLifetime)
|
||||
} else {
|
||||
tokenExpiresAt = now.Add(p.refreshLifetime)
|
||||
}
|
||||
claims := &jwtClaims{
|
||||
RegisteredClaims: jwt.RegisteredClaims{
|
||||
Subject: userID.String(),
|
||||
ExpiresAt: jwt.NewNumericDate(tokenExpiresAt),
|
||||
NotBefore: jwt.NewNumericDate(now),
|
||||
IssuedAt: jwt.NewNumericDate(now),
|
||||
ID: uuid.NewString(),
|
||||
},
|
||||
IsAccess: isAccess,
|
||||
Role: role,
|
||||
}
|
||||
t := jwt.NewWithClaims(jwt.SigningMethodRS256, claims)
|
||||
|
||||
payload, err := t.SignedString(p.privateKey)
|
||||
if err != nil {
|
||||
slog.Error("failed to sign jwt", "error", err)
|
||||
return nil, ErrFailedToSign
|
||||
}
|
||||
return &dto.Token{Payload: payload}, nil
|
||||
}
|
||||
|
||||
// TODO refactor maybe delete
|
||||
func (p *provider) ValidateUserDataInToken(u *dto.UserDataInToken) error {
|
||||
if u == nil {
|
||||
return ErrInvalidUserDataInToken
|
||||
}
|
||||
|
||||
switch {
|
||||
case u.TokenID == uuid.Nil:
|
||||
return fmt.Errorf("%w: unexpected nil token id", ErrInvalidUserDataInToken)
|
||||
case u.UserID == uuid.Nil:
|
||||
return fmt.Errorf("%w: unexpected nil user id", ErrInvalidUserDataInToken)
|
||||
case u.IssuedAt.IsZero():
|
||||
return fmt.Errorf("%w: unexpected zero issued at", ErrInvalidUserDataInToken)
|
||||
case u.Email != nil && *u.Email == "":
|
||||
return fmt.Errorf("%w: unexpected empty email", ErrInvalidUserDataInToken)
|
||||
case u.PhoneNumber != nil && *u.PhoneNumber == "":
|
||||
return fmt.Errorf("%w: unexpected empty phone number", ErrInvalidUserDataInToken)
|
||||
case u.ExpiresAt.IsZero():
|
||||
return fmt.Errorf("%w: unexpected zero expires at", ErrInvalidUserDataInToken)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (p *provider) readKeyFunc(token *jwt.Token) (interface{}, error) {
|
||||
if token.Method != jwt.SigningMethodRS256 {
|
||||
return nil, fmt.Errorf("unexpected signing method: %v", token.Header["alg"])
|
||||
}
|
||||
return p.publicKey, nil
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
package jwtprovider
|
||||
|
||||
import (
|
||||
"crypto/rsa"
|
||||
"fmt"
|
||||
"os"
|
||||
|
||||
"github.com/golang-jwt/jwt/v5"
|
||||
)
|
||||
|
||||
func readPrivateKeyFromFile(path string) (*rsa.PrivateKey, error) {
|
||||
key, err := os.ReadFile(path)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to read public key: %w", err)
|
||||
}
|
||||
|
||||
privateKey, err := jwt.ParseRSAPrivateKeyFromPEM(key)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to parse private key: %w", err)
|
||||
}
|
||||
return privateKey, nil
|
||||
}
|
||||
|
||||
func readPublicKeyFromFile(path string) (*rsa.PublicKey, error) {
|
||||
key, err := os.ReadFile(path)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to read public key: %w", err)
|
||||
}
|
||||
|
||||
privateKey, err := jwt.ParseRSAPublicKeyFromPEM(key)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to parse private key: %w", err)
|
||||
}
|
||||
return privateKey, nil
|
||||
}
|
||||
Vendored
+43
@@ -0,0 +1,43 @@
|
||||
package cache
|
||||
|
||||
import (
|
||||
"context"
|
||||
"time"
|
||||
|
||||
"github.com/redis/go-redis/v9"
|
||||
|
||||
"gitea.privcloud.tech/mtusi2026/internal/config"
|
||||
)
|
||||
|
||||
const defaultRedisPort = 6379
|
||||
|
||||
// OperationTimeout bounds each optional cache operation independently of the request.
|
||||
const OperationTimeout = 300 * time.Millisecond
|
||||
|
||||
type Client struct {
|
||||
*redis.Client
|
||||
}
|
||||
|
||||
func New(cfg *config.Config) *Client {
|
||||
if cfg.Redis.Port == 0 {
|
||||
cfg.Redis.Port = defaultRedisPort
|
||||
}
|
||||
|
||||
return &Client{
|
||||
Client: redis.NewClient(cfg.Redis.BuildRedisOptions()),
|
||||
}
|
||||
}
|
||||
|
||||
func (c *Client) Ping(ctx context.Context) error {
|
||||
ctx, cancel := context.WithTimeout(ctx, OperationTimeout)
|
||||
defer cancel()
|
||||
return c.Client.Ping(ctx).Err()
|
||||
}
|
||||
|
||||
func (c *Client) Start(ctx context.Context) error {
|
||||
return c.Ping(ctx)
|
||||
}
|
||||
|
||||
func (c *Client) Stop(_ context.Context) error {
|
||||
return c.Client.Close()
|
||||
}
|
||||
@@ -0,0 +1,71 @@
|
||||
package encrypting
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/rand"
|
||||
"crypto/subtle"
|
||||
"encoding/base64"
|
||||
"fmt"
|
||||
"strings"
|
||||
|
||||
"golang.org/x/crypto/argon2"
|
||||
)
|
||||
|
||||
const (
|
||||
argon2idMemory = 64 * 1024 // KiB
|
||||
argon2idTime = 3
|
||||
argon2idThreads = 4
|
||||
argon2idSaltLen = 16
|
||||
argon2idKeyLen = 32
|
||||
// Only this bounded profile is accepted; stored parameters cannot request arbitrary resources.
|
||||
argon2idPrefix = "$argon2id$v=19$m=65536,t=3,p=4$"
|
||||
)
|
||||
|
||||
func (e *encryptor) EncryptSecretUsingArgon2id(ctx context.Context, secret string) (string, error) {
|
||||
if err := ctx.Err(); err != nil {
|
||||
return "", err
|
||||
}
|
||||
var salt [argon2idSaltLen]byte
|
||||
if _, err := rand.Read(salt[:]); err != nil {
|
||||
return "", fmt.Errorf("%w: %w", ErrFailedToEncryptPassword, err)
|
||||
}
|
||||
key := argon2.IDKey([]byte(secret), salt[:], argon2idTime, argon2idMemory, argon2idThreads, argon2idKeyLen)
|
||||
if err := ctx.Err(); err != nil {
|
||||
return "", err
|
||||
}
|
||||
return argon2idPrefix + base64.RawStdEncoding.EncodeToString(salt[:]) + "$" + base64.RawStdEncoding.EncodeToString(key), nil
|
||||
}
|
||||
|
||||
func (e *encryptor) CompareHashAndSecretUsingArgon2id(ctx context.Context, hash, secret string) error {
|
||||
if err := ctx.Err(); err != nil {
|
||||
return err
|
||||
}
|
||||
encoding := base64.RawStdEncoding.Strict()
|
||||
if len(hash) != len(argon2idPrefix)+encoding.EncodedLen(argon2idSaltLen)+1+encoding.EncodedLen(argon2idKeyLen) {
|
||||
return ErrFailedToComparePasswords
|
||||
}
|
||||
payload, ok := strings.CutPrefix(hash, argon2idPrefix)
|
||||
if !ok {
|
||||
return ErrFailedToComparePasswords
|
||||
}
|
||||
saltText, keyText, ok := strings.Cut(payload, "$")
|
||||
if !ok {
|
||||
return ErrFailedToComparePasswords
|
||||
}
|
||||
salt, err := encoding.DecodeString(saltText)
|
||||
if err != nil || len(salt) != argon2idSaltLen {
|
||||
return ErrFailedToComparePasswords
|
||||
}
|
||||
storedKey, err := encoding.DecodeString(keyText)
|
||||
if err != nil || len(storedKey) != argon2idKeyLen {
|
||||
return ErrFailedToComparePasswords
|
||||
}
|
||||
key := argon2.IDKey([]byte(secret), salt, argon2idTime, argon2idMemory, argon2idThreads, argon2idKeyLen)
|
||||
if err = ctx.Err(); err != nil {
|
||||
return err
|
||||
}
|
||||
if subtle.ConstantTimeCompare(storedKey, key) != 1 {
|
||||
return ErrFailedToComparePasswords
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,57 @@
|
||||
package encrypting
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/sha256"
|
||||
"encoding/hex"
|
||||
|
||||
"golang.org/x/crypto/bcrypt"
|
||||
)
|
||||
|
||||
type encryptor struct {
|
||||
cost int
|
||||
generateFromPasswordFunc func([]byte, int) ([]byte, error)
|
||||
compareHashAndPasswordFunc func([]byte, []byte) error
|
||||
}
|
||||
|
||||
func New() Encryptor {
|
||||
return &encryptor{
|
||||
cost: bcrypt.DefaultCost,
|
||||
generateFromPasswordFunc: bcrypt.GenerateFromPassword,
|
||||
compareHashAndPasswordFunc: bcrypt.CompareHashAndPassword,
|
||||
}
|
||||
}
|
||||
|
||||
func (e *encryptor) EncryptSecret(_ context.Context, secret string) (string, error) {
|
||||
res, err := e.generateFromPasswordFunc([]byte(secret), e.cost)
|
||||
if err != nil {
|
||||
return "", ErrFailedToEncryptPassword
|
||||
}
|
||||
return string(res), nil
|
||||
}
|
||||
|
||||
func (e *encryptor) EncryptSecretUsingSum256(_ context.Context, secret string) (string, error) {
|
||||
sum := sha256.Sum256([]byte(secret))
|
||||
res, err := e.generateFromPasswordFunc([]byte(hex.EncodeToString(sum[:])), e.cost)
|
||||
if err != nil {
|
||||
return "", ErrFailedToEncryptPassword
|
||||
}
|
||||
return string(res), nil
|
||||
}
|
||||
|
||||
func (e *encryptor) CompareHashAndSecret(_ context.Context, hash, password string) error {
|
||||
err := e.compareHashAndPasswordFunc([]byte(hash), []byte(password))
|
||||
if err != nil {
|
||||
return ErrFailedToComparePasswords
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (e *encryptor) CompareHashAndSecretUsingSum256(_ context.Context, hash, password string) error {
|
||||
sum := sha256.Sum256([]byte(password))
|
||||
err := e.compareHashAndPasswordFunc([]byte(hash), []byte(hex.EncodeToString(sum[:])))
|
||||
if err != nil {
|
||||
return ErrFailedToComparePasswords
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
package encrypting
|
||||
|
||||
import "errors"
|
||||
|
||||
var (
|
||||
ErrFailedToEncryptPassword = errors.New("failed to encrypt password")
|
||||
ErrFailedToComparePasswords = errors.New("failed to compare passwords")
|
||||
)
|
||||
@@ -0,0 +1,12 @@
|
||||
package encrypting
|
||||
|
||||
import "context"
|
||||
|
||||
type Encryptor interface {
|
||||
EncryptSecretUsingArgon2id(ctx context.Context, secret string) (string, error)
|
||||
CompareHashAndSecretUsingArgon2id(ctx context.Context, hash, secret string) error
|
||||
EncryptSecret(ctx context.Context, secret string) (string, error)
|
||||
EncryptSecretUsingSum256(_ context.Context, secret string) (string, error)
|
||||
CompareHashAndSecret(ctx context.Context, hash, secret string) error
|
||||
CompareHashAndSecretUsingSum256(ctx context.Context, hash, secret string) error
|
||||
}
|
||||
@@ -0,0 +1,168 @@
|
||||
package migrator
|
||||
|
||||
import (
|
||||
"context"
|
||||
"io/fs"
|
||||
"log/slog"
|
||||
|
||||
"github.com/jackc/pgx/v5"
|
||||
"github.com/jackc/tern/v2/migrate"
|
||||
|
||||
"gitea.privcloud.tech/mtusi2026/internal/config"
|
||||
"gitea.privcloud.tech/mtusi2026/internal/pkg/apperr"
|
||||
"gitea.privcloud.tech/mtusi2026/migrations"
|
||||
)
|
||||
|
||||
type Migrator interface {
|
||||
MigrateUp(ctx context.Context) error
|
||||
MigrateDown(ctx context.Context) error
|
||||
MigrateTo(ctx context.Context, version int32) error
|
||||
GetVersion(ctx context.Context) (int32, error)
|
||||
Configure(ctx context.Context) error
|
||||
Close(ctx context.Context) error
|
||||
Start(ctx context.Context) error
|
||||
Stop(ctx context.Context) error
|
||||
}
|
||||
|
||||
type migrator struct {
|
||||
cfg *config.Config
|
||||
conn *pgx.Conn
|
||||
migrator *migrate.Migrator
|
||||
migrations fs.FS
|
||||
configured bool
|
||||
closed bool
|
||||
}
|
||||
|
||||
func New(cfg *config.Config) Migrator {
|
||||
return &migrator{
|
||||
cfg: cfg,
|
||||
conn: nil,
|
||||
migrator: nil,
|
||||
migrations: migrations.Migrations,
|
||||
configured: false,
|
||||
closed: false,
|
||||
}
|
||||
}
|
||||
|
||||
func (m *migrator) MigrateUp(ctx context.Context) error {
|
||||
if !m.configured {
|
||||
return apperr.New(apperr.CodeInternal, "migrator was not configured")
|
||||
}
|
||||
return m.migrator.Migrate(ctx)
|
||||
}
|
||||
|
||||
func (m *migrator) MigrateDown(ctx context.Context) error {
|
||||
if !m.configured {
|
||||
return apperr.New(apperr.CodeInternal, "migrator was not configured")
|
||||
}
|
||||
return m.migrator.MigrateTo(ctx, 0)
|
||||
}
|
||||
|
||||
func (m *migrator) MigrateTo(ctx context.Context, version int32) error {
|
||||
if !m.configured {
|
||||
return apperr.New(apperr.CodeInternal, "migrator was not configured")
|
||||
}
|
||||
return m.migrator.MigrateTo(ctx, version)
|
||||
}
|
||||
|
||||
func (m *migrator) GetVersion(ctx context.Context) (int32, error) {
|
||||
if !m.configured {
|
||||
return -1, apperr.New(apperr.CodeInternal, "migrator was not configured")
|
||||
}
|
||||
return m.migrator.GetCurrentVersion(ctx)
|
||||
}
|
||||
|
||||
func (m *migrator) Configure(ctx context.Context) error {
|
||||
if err := m.initConn(ctx); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := m.initMigrator(ctx); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := m.loadMigrations(); err != nil {
|
||||
return err
|
||||
}
|
||||
m.configured = true
|
||||
return nil
|
||||
}
|
||||
|
||||
func (m *migrator) Close(ctx context.Context) error {
|
||||
return m.closeConn(ctx)
|
||||
}
|
||||
|
||||
func (m *migrator) Start(ctx context.Context) error {
|
||||
if !m.cfg.Postgres.GetRunMigrations() {
|
||||
slog.Info("flag run migrations is disabled: skipping migrating")
|
||||
return nil
|
||||
}
|
||||
|
||||
err := m.Configure(ctx)
|
||||
if err != nil {
|
||||
slog.Error("failed to configure migrator", "error", err)
|
||||
return err
|
||||
}
|
||||
err = m.MigrateUp(ctx)
|
||||
if err != nil {
|
||||
slog.Error("failed to migrate database up", "error", err)
|
||||
return err
|
||||
}
|
||||
|
||||
if err = m.Close(ctx); err != nil {
|
||||
slog.Error("failed close connection to database", "error", err)
|
||||
return err
|
||||
}
|
||||
|
||||
m.closed = true
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (m *migrator) Stop(ctx context.Context) error {
|
||||
if !m.cfg.Postgres.GetRunMigrations() {
|
||||
return nil
|
||||
}
|
||||
|
||||
if !m.closed {
|
||||
err := m.conn.Close(ctx)
|
||||
if err != nil {
|
||||
slog.Error("failed close connection to database", "error", err)
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (m *migrator) loadMigrations() (err error) {
|
||||
err = m.migrator.LoadMigrations(m.migrations)
|
||||
if err != nil {
|
||||
slog.Error("failed to load migrations", "error", err)
|
||||
return apperr.New(apperr.CodeInternal, "failed to load migrations")
|
||||
}
|
||||
slog.Info("successfully loaded migrations", "error", err)
|
||||
return nil
|
||||
}
|
||||
|
||||
func (m *migrator) initConn(ctx context.Context) (err error) {
|
||||
m.conn, err = pgx.Connect(ctx, m.cfg.Postgres.GetURI())
|
||||
if err != nil {
|
||||
slog.Error("failed to create connection to database", "error", err)
|
||||
return apperr.New(apperr.CodeInternal, "failed to create connection to database")
|
||||
}
|
||||
slog.Info("connected to database", "db", m.cfg.Postgres.Database)
|
||||
return nil
|
||||
}
|
||||
|
||||
func (m *migrator) initMigrator(ctx context.Context) (err error) {
|
||||
m.migrator, err = migrate.NewMigrator(ctx, m.conn, m.cfg.Postgres.GetVersionTableName())
|
||||
if err != nil {
|
||||
slog.Error("failed to initialize migrator", "error", err)
|
||||
return apperr.New(apperr.CodeInternal, "failed to initialize migrator")
|
||||
}
|
||||
slog.Info("successfully initialized migrator")
|
||||
return nil
|
||||
}
|
||||
|
||||
func (m *migrator) closeConn(ctx context.Context) error {
|
||||
return m.conn.Close(ctx)
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
package postgres
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"github.com/jackc/pgx/v5"
|
||||
pgxUUID "github.com/vgarvardt/pgx-google-uuid/v5"
|
||||
)
|
||||
|
||||
type AfterConnect func(ctx context.Context, conn *pgx.Conn) error
|
||||
|
||||
func AddUUIDSupport(_ context.Context, conn *pgx.Conn) error {
|
||||
pgxUUID.Register(conn.TypeMap())
|
||||
return nil
|
||||
}
|
||||
func WithEnumTypeSupport(enumName string) AfterConnect {
|
||||
return func(ctx context.Context, conn *pgx.Conn) error {
|
||||
dt, err := conn.LoadType(ctx, enumName)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
conn.TypeMap().RegisterType(dt)
|
||||
return nil
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
package postgres
|
||||
|
||||
type MigrationConfig interface {
|
||||
GetURI() string
|
||||
GetVersionTableName() string
|
||||
GetRunMigrations() bool
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
package postgres
|
||||
|
||||
import (
|
||||
"errors"
|
||||
)
|
||||
|
||||
var (
|
||||
errCreatingPool = errors.New("failed to create postgres pool")
|
||||
errParseConfig = errors.New("failed to parse postgres config")
|
||||
)
|
||||
@@ -0,0 +1,15 @@
|
||||
package postgres
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"github.com/jackc/pgx/v5"
|
||||
"github.com/jackc/pgx/v5/pgconn"
|
||||
)
|
||||
|
||||
type Conn interface {
|
||||
SendBatch(ctx context.Context, b *pgx.Batch) pgx.BatchResults
|
||||
Exec(ctx context.Context, sql string, arguments ...any) (commandTag pgconn.CommandTag, err error)
|
||||
Query(ctx context.Context, sql string, args ...any) (pgx.Rows, error)
|
||||
QueryRow(ctx context.Context, sql string, args ...any) pgx.Row
|
||||
}
|
||||
@@ -0,0 +1,80 @@
|
||||
package postgres
|
||||
|
||||
import (
|
||||
"context"
|
||||
"log/slog"
|
||||
|
||||
"github.com/jackc/pgx/v5"
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
"github.com/jackc/pgx/v5/tracelog"
|
||||
|
||||
pgxslog "github.com/mcosta74/pgx-slog"
|
||||
)
|
||||
|
||||
type ConfigWithLog interface {
|
||||
GetLogLevel() string
|
||||
}
|
||||
|
||||
type ConfigWithMaxConn interface {
|
||||
GetMaxConnections() int32
|
||||
}
|
||||
|
||||
func getLevelFromConfig(cfg MigrationConfig) tracelog.LogLevel {
|
||||
if logCfg, ok := cfg.(ConfigWithLog); ok {
|
||||
lvl, _ := tracelog.LogLevelFromString(logCfg.GetLogLevel())
|
||||
return lvl
|
||||
}
|
||||
return tracelog.LogLevelError
|
||||
}
|
||||
|
||||
func addMaxConnectionsToCfg(cfg any, poolCfg *pgxpool.Config) {
|
||||
if connCfg, ok := cfg.(ConfigWithMaxConn); ok {
|
||||
poolCfg.MaxConns = connCfg.GetMaxConnections()
|
||||
}
|
||||
}
|
||||
|
||||
func New(cfg MigrationConfig, afterConnect ...AfterConnect) *pgxpool.Pool {
|
||||
lvl := getLevelFromConfig(cfg)
|
||||
|
||||
if len(afterConnect) == 0 {
|
||||
afterConnect = []AfterConnect{AddUUIDSupport}
|
||||
}
|
||||
|
||||
poolConfig, err := pgxpool.ParseConfig(cfg.GetURI())
|
||||
if err != nil {
|
||||
slog.Error("failed to parse postgres config", "error", err)
|
||||
panic(err)
|
||||
}
|
||||
|
||||
addMaxConnectionsToCfg(cfg, poolConfig)
|
||||
|
||||
poolConfig.ConnConfig.Tracer = &tracelog.TraceLog{
|
||||
Logger: pgxslog.NewLogger(slog.Default()),
|
||||
LogLevel: lvl,
|
||||
Config: &tracelog.TraceLogConfig{
|
||||
TimeKey: "ts",
|
||||
},
|
||||
}
|
||||
|
||||
poolConfig.AfterConnect = load(afterConnect...)
|
||||
|
||||
pool, err := pgxpool.NewWithConfig(context.Background(), poolConfig)
|
||||
if err != nil {
|
||||
slog.Error("failed to create postgres pool", "error", err)
|
||||
panic(err)
|
||||
}
|
||||
|
||||
slog.Info("successfully connected to postgres pool")
|
||||
return pool
|
||||
}
|
||||
|
||||
func load(afterConnects ...AfterConnect) func(ctx context.Context, conn *pgx.Conn) error {
|
||||
return func(ctx context.Context, conn *pgx.Conn) error {
|
||||
for _, afterConnect := range afterConnects {
|
||||
if err := afterConnect(ctx, conn); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,59 @@
|
||||
package txmanager
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"log/slog"
|
||||
|
||||
"github.com/jackc/pgx/v5"
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
)
|
||||
|
||||
type TransactionManager struct {
|
||||
pool *pgxpool.Pool
|
||||
}
|
||||
|
||||
func New(pool *pgxpool.Pool) *TransactionManager {
|
||||
return &TransactionManager{
|
||||
pool: pool,
|
||||
}
|
||||
}
|
||||
|
||||
func (tm *TransactionManager) RunInTransaction(ctx context.Context, opts *pgx.TxOptions, fn func(tx pgx.Tx) error) (err error) {
|
||||
var tx pgx.Tx
|
||||
|
||||
if opts != nil {
|
||||
tx, err = tm.pool.BeginTx(ctx, *opts)
|
||||
} else {
|
||||
tx, err = tm.pool.Begin(ctx)
|
||||
}
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to begin transaction: %w", err)
|
||||
}
|
||||
|
||||
var committed bool
|
||||
|
||||
defer func() {
|
||||
if p := recover(); p != nil {
|
||||
err = fmt.Errorf("panic in transaction: %v", p)
|
||||
}
|
||||
if !committed {
|
||||
rollbackErr := tx.Rollback(ctx)
|
||||
if rollbackErr != nil && !errors.Is(rollbackErr, pgx.ErrTxClosed) {
|
||||
slog.Error("failed to rollback transaction", "error", rollbackErr)
|
||||
}
|
||||
}
|
||||
}()
|
||||
|
||||
if err = fn(tx); err != nil {
|
||||
return fmt.Errorf("failed to execute transaction: %w", err)
|
||||
}
|
||||
|
||||
if err = tx.Commit(ctx); err != nil {
|
||||
return fmt.Errorf("failed to commit transaction: %w", err)
|
||||
}
|
||||
|
||||
committed = true
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,245 @@
|
||||
package framework
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"log/slog"
|
||||
"mime"
|
||||
"net/http"
|
||||
"strconv"
|
||||
"strings"
|
||||
|
||||
"github.com/go-chi/chi/v5"
|
||||
v10 "github.com/go-playground/validator/v10"
|
||||
"github.com/google/uuid"
|
||||
|
||||
"gitea.privcloud.tech/mtusi2026/internal/dto"
|
||||
"gitea.privcloud.tech/mtusi2026/internal/gen/contracts"
|
||||
"gitea.privcloud.tech/mtusi2026/internal/pkg/apperr"
|
||||
"gitea.privcloud.tech/mtusi2026/internal/pkg/auth/jwtprovider"
|
||||
"gitea.privcloud.tech/mtusi2026/internal/pkg/rest/headers"
|
||||
"gitea.privcloud.tech/mtusi2026/internal/pkg/validator"
|
||||
)
|
||||
|
||||
func validate(ctx context.Context, v *validator.ValidatorImpl, value any) error {
|
||||
err := v.ValidateCtx(ctx, value)
|
||||
if err == nil {
|
||||
return nil
|
||||
}
|
||||
var fieldErrors v10.ValidationErrors
|
||||
if errors.As(err, &fieldErrors) {
|
||||
return apperr.Wrap(err, apperr.CodeValidation, "invalid request fields")
|
||||
}
|
||||
return apperr.Wrap(err, apperr.CodeInternal, "validation failed")
|
||||
}
|
||||
|
||||
func Validate(w http.ResponseWriter, r *http.Request, v *validator.ValidatorImpl, value any) bool {
|
||||
if err := validate(r.Context(), v, value); err != nil {
|
||||
JSONError(r.Context(), w, err)
|
||||
return false
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
func JSONResponse(w http.ResponseWriter, status int, body any) {
|
||||
w.Header().Set(headers.HeaderContentType, "application/json")
|
||||
w.WriteHeader(status)
|
||||
|
||||
if status == http.StatusNoContent {
|
||||
return
|
||||
}
|
||||
|
||||
if err := json.NewEncoder(w).Encode(body); err != nil {
|
||||
wrapped := apperr.Wrap(err, apperr.CodeInternal, "failed json encode")
|
||||
slog.Error("response", "error", wrapped)
|
||||
}
|
||||
}
|
||||
|
||||
func JSONError(ctx context.Context, w http.ResponseWriter, err error) {
|
||||
if err == nil {
|
||||
return
|
||||
}
|
||||
|
||||
requestId, ok := ctx.Value(headers.HeaderRequestID).(uuid.UUID)
|
||||
if !ok {
|
||||
requestId = uuid.New()
|
||||
}
|
||||
w.Header().Set(headers.HeaderRequestID, requestId.String())
|
||||
|
||||
appErr := apperr.As(err)
|
||||
if appErr == nil {
|
||||
appErr = apperr.As(apperr.New(apperr.CodeInternal, "internal server error"))
|
||||
}
|
||||
if appErr.Code().HTTPStatus() == http.StatusUnauthorized && w.Header().Get("WWW-Authenticate") == "" {
|
||||
w.Header().Set("WWW-Authenticate", `Bearer realm="messenger"`)
|
||||
}
|
||||
|
||||
slog.Error("response", "error", err, "status", appErr.Code().HTTPStatus(), "requestId", requestId.String())
|
||||
|
||||
var code contracts.ErrorErrorCode
|
||||
switch appErr.Code() {
|
||||
case apperr.CodeBadRequest, apperr.CodeValidation:
|
||||
code = contracts.InvalidRequest
|
||||
case apperr.CodeUnauthorized:
|
||||
code = contracts.Unauthorized
|
||||
case apperr.CodeNotFound:
|
||||
code = contracts.NotFound
|
||||
case apperr.CodeAlreadyExists, apperr.CodeConflict:
|
||||
code = contracts.Conflict
|
||||
case apperr.CodePayloadTooLarge:
|
||||
code = contracts.PayloadTooLarge
|
||||
case apperr.CodeTooManyRequests:
|
||||
code = contracts.RateLimited
|
||||
case apperr.CodeServiceUnavailable, apperr.CodeUnavailable:
|
||||
code = contracts.Unavailable
|
||||
case apperr.CodeUnsupportedMediaType:
|
||||
code = contracts.UnsupportedMediaType
|
||||
default:
|
||||
code = contracts.InternalError
|
||||
}
|
||||
JSONResponse(w, appErr.Code().HTTPStatus(), contracts.Error{
|
||||
Error: struct {
|
||||
Code contracts.ErrorErrorCode `json:"code"`
|
||||
Message string `json:"message"`
|
||||
RequestId string `json:"request_id"`
|
||||
}{
|
||||
Code: code,
|
||||
Message: appErr.Message(),
|
||||
RequestId: requestId.String(),
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
func Decode(w http.ResponseWriter, r *http.Request, object any) bool {
|
||||
mediaType, params, err := mime.ParseMediaType(r.Header.Get(headers.HeaderContentType))
|
||||
if err != nil || mediaType != "application/json" ||
|
||||
(params["charset"] != "" && !strings.EqualFold(params["charset"], "utf-8")) {
|
||||
JSONError(r.Context(), w, apperr.New(apperr.CodeUnsupportedMediaType, "expected application/json"))
|
||||
return false
|
||||
}
|
||||
decoder := json.NewDecoder(r.Body)
|
||||
decoder.DisallowUnknownFields()
|
||||
if err := decoder.Decode(object); err != nil {
|
||||
JSONError(r.Context(), w, apperr.Wrap(err, apperr.CodeBadRequest, "failed decode"))
|
||||
return false
|
||||
}
|
||||
var trailing any
|
||||
if err := decoder.Decode(&trailing); err != io.EOF {
|
||||
JSONError(r.Context(), w, apperr.New(apperr.CodeBadRequest, "expected one JSON object"))
|
||||
return false
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
func PathParam(r *http.Request, key string) string {
|
||||
return chi.URLParam(r, key)
|
||||
}
|
||||
|
||||
func QueryParam(r *http.Request, key string) string {
|
||||
return r.URL.Query().Get(key)
|
||||
}
|
||||
|
||||
func HeaderParam(r *http.Request, key string) string {
|
||||
return r.Header.Get(key)
|
||||
}
|
||||
|
||||
func ParseIDFromPathParam(ctx context.Context, w http.ResponseWriter, r *http.Request, key string) (uuid.UUID, error) {
|
||||
rawID := PathParam(r, key)
|
||||
id, err := uuid.Parse(rawID)
|
||||
if err != nil {
|
||||
JSONError(ctx, w, apperr.New(apperr.CodeValidation, fmt.Sprintf("provided invalid %s", key)))
|
||||
return uuid.Nil, err
|
||||
}
|
||||
return id, nil
|
||||
}
|
||||
|
||||
func ParseIDFromQueryParam(ctx context.Context, w http.ResponseWriter, r *http.Request, key string) (uuid.UUID, error) {
|
||||
rawID := QueryParam(r, key)
|
||||
id, err := uuid.Parse(rawID)
|
||||
if err != nil {
|
||||
JSONError(ctx, w, apperr.New(apperr.CodeValidation, fmt.Sprintf("provided invalid %s", key)))
|
||||
return uuid.Nil, err
|
||||
}
|
||||
return id, nil
|
||||
}
|
||||
|
||||
func ParseIDFromHeaderParam(ctx context.Context, w http.ResponseWriter, r *http.Request, key string) (uuid.UUID, error) {
|
||||
rawID := HeaderParam(r, key)
|
||||
id, err := uuid.Parse(rawID)
|
||||
if err != nil {
|
||||
JSONError(ctx, w, apperr.New(apperr.CodeUnauthorized, "missing or invalid user ID"))
|
||||
return uuid.Nil, err
|
||||
}
|
||||
return id, nil
|
||||
}
|
||||
|
||||
func Header(r *http.Request, header string) (string, bool) {
|
||||
return r.Header.Get(header), r.Header.Get(header) != ""
|
||||
}
|
||||
|
||||
func Token(r *http.Request) (string, bool) {
|
||||
foundHeader := r.Header.Get(headers.HeaderAuthorization)
|
||||
if foundHeader == "" {
|
||||
return "", false
|
||||
}
|
||||
|
||||
token, found := strings.CutPrefix(foundHeader, "Bearer ")
|
||||
if !found {
|
||||
return "", false
|
||||
}
|
||||
|
||||
return token, true
|
||||
}
|
||||
|
||||
func ParseToken(r *http.Request, provider jwtprovider.Provider) (*dto.UserDataInToken, error) {
|
||||
foundHeader := r.Header.Get(headers.HeaderAuthorization)
|
||||
if foundHeader == "" {
|
||||
return nil, apperr.New(apperr.CodeUnauthorized, "missing authorization header")
|
||||
}
|
||||
|
||||
token, found := strings.CutPrefix(foundHeader, "Bearer ")
|
||||
if !found {
|
||||
return nil, apperr.New(apperr.CodeUnauthorized, "invalid authorization header")
|
||||
}
|
||||
|
||||
userData, err := provider.ParseVerified(&dto.Token{Payload: token})
|
||||
if err != nil {
|
||||
return nil, apperr.Wrap(err, apperr.CodeUnauthorized, "invalid token")
|
||||
}
|
||||
|
||||
return userData, nil
|
||||
}
|
||||
|
||||
func PageParams(w http.ResponseWriter, r *http.Request) (*int, *uuid.UUID, bool) {
|
||||
query := r.URL.Query()
|
||||
var limit *int
|
||||
if values, exists := query["limit"]; exists {
|
||||
if len(values) != 1 {
|
||||
JSONError(r.Context(), w, apperr.New(apperr.CodeBadRequest, "invalid limit"))
|
||||
return nil, nil, false
|
||||
}
|
||||
value, err := strconv.Atoi(values[0])
|
||||
if err != nil || value < 1 || value > 100 {
|
||||
JSONError(r.Context(), w, apperr.New(apperr.CodeBadRequest, "invalid limit"))
|
||||
return nil, nil, false
|
||||
}
|
||||
limit = &value
|
||||
}
|
||||
var afterID *uuid.UUID
|
||||
if values, exists := query["cursor"]; exists {
|
||||
if len(values) != 1 {
|
||||
JSONError(r.Context(), w, apperr.New(apperr.CodeBadRequest, "invalid cursor"))
|
||||
return nil, nil, false
|
||||
}
|
||||
id, err := uuid.Parse(values[0])
|
||||
if err != nil || id == uuid.Nil {
|
||||
JSONError(r.Context(), w, apperr.New(apperr.CodeBadRequest, "invalid cursor"))
|
||||
return nil, nil, false
|
||||
}
|
||||
afterID = &id
|
||||
}
|
||||
return limit, afterID, true
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
package headers
|
||||
|
||||
const (
|
||||
HeaderContentType = "Content-Type"
|
||||
HeaderRequestID = "X-Request-Id"
|
||||
HeaderUserID = "X-User-Id"
|
||||
HeaderAuthorization = "Authorization"
|
||||
)
|
||||
@@ -0,0 +1,74 @@
|
||||
package middleware
|
||||
|
||||
import (
|
||||
"context"
|
||||
"net/http"
|
||||
|
||||
"gitea.privcloud.tech/mtusi2026/internal/dto"
|
||||
"gitea.privcloud.tech/mtusi2026/internal/pkg/apperr"
|
||||
"gitea.privcloud.tech/mtusi2026/internal/pkg/rest/framework"
|
||||
"gitea.privcloud.tech/mtusi2026/internal/pkg/types/role"
|
||||
)
|
||||
|
||||
var _ AuthMiddleware = (*authMiddleware)(nil)
|
||||
|
||||
type AuthMiddleware interface {
|
||||
WithPrivateAccess(next http.Handler) http.Handler
|
||||
WithAdminAccess(next http.Handler) http.Handler
|
||||
}
|
||||
|
||||
type SessionVerifier interface {
|
||||
VerifySession(ctx context.Context, token dto.Token) (*dto.UserDataInToken, error)
|
||||
}
|
||||
|
||||
type authMiddleware struct {
|
||||
verifier SessionVerifier
|
||||
}
|
||||
|
||||
func NewAuthMiddleware(verifier SessionVerifier) AuthMiddleware {
|
||||
return &authMiddleware{verifier: verifier}
|
||||
}
|
||||
|
||||
func (a *authMiddleware) WithPrivateAccess(next http.Handler) http.Handler {
|
||||
return a.privateAccessCheckCallback(next)
|
||||
}
|
||||
|
||||
func (a *authMiddleware) WithAdminAccess(next http.Handler) http.Handler {
|
||||
return a.operatorAccessCheckCallback(role.Admin, next)
|
||||
}
|
||||
|
||||
func (a *authMiddleware) privateAccessCheckCallback(next http.Handler) http.HandlerFunc {
|
||||
return func(w http.ResponseWriter, r *http.Request) {
|
||||
if _, err := a.verifySession(r); err != nil {
|
||||
framework.JSONError(r.Context(), w, err)
|
||||
return
|
||||
}
|
||||
|
||||
next.ServeHTTP(w, r)
|
||||
}
|
||||
}
|
||||
|
||||
func (a *authMiddleware) operatorAccessCheckCallback(expectedRole role.Role, next http.Handler) http.HandlerFunc {
|
||||
return func(w http.ResponseWriter, r *http.Request) {
|
||||
u, err := a.verifySession(r)
|
||||
if err != nil {
|
||||
framework.JSONError(r.Context(), w, err)
|
||||
return
|
||||
}
|
||||
|
||||
if u.Role != role.Admin && u.Role != expectedRole {
|
||||
framework.JSONError(r.Context(), w, apperr.New(apperr.CodeForbidden, "insufficient permissions"))
|
||||
return
|
||||
}
|
||||
|
||||
next.ServeHTTP(w, r)
|
||||
}
|
||||
}
|
||||
|
||||
func (a *authMiddleware) verifySession(r *http.Request) (*dto.UserDataInToken, error) {
|
||||
token, found := framework.Token(r)
|
||||
if !found || token == "" {
|
||||
return nil, apperr.New(apperr.CodeUnauthorized, "missing or invalid bearer token")
|
||||
}
|
||||
return a.verifier.VerifySession(r.Context(), dto.Token{Payload: token})
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
package middleware
|
||||
|
||||
import (
|
||||
"log/slog"
|
||||
"net/http"
|
||||
"time"
|
||||
|
||||
"github.com/go-chi/chi/v5/middleware"
|
||||
|
||||
"gitea.privcloud.tech/mtusi2026/internal/pkg/rest/headers"
|
||||
)
|
||||
|
||||
func LoggingMiddleware() Middleware {
|
||||
return func(next http.Handler) http.Handler {
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
started := time.Now()
|
||||
wrapped := middleware.NewWrapResponseWriter(w, r.ProtoMajor)
|
||||
next.ServeHTTP(wrapped, r)
|
||||
|
||||
status := wrapped.Status()
|
||||
if status == 0 {
|
||||
status = http.StatusOK
|
||||
}
|
||||
slog.InfoContext(r.Context(), "http request",
|
||||
"method", r.Method,
|
||||
"path", r.URL.Path,
|
||||
"status", status,
|
||||
"duration", time.Since(started),
|
||||
"bytes", wrapped.BytesWritten(),
|
||||
"request_id", w.Header().Get(headers.HeaderRequestID),
|
||||
)
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,5 @@
|
||||
package middleware
|
||||
|
||||
import "net/http"
|
||||
|
||||
type Middleware = func(http.Handler) http.Handler
|
||||
@@ -0,0 +1,22 @@
|
||||
package middleware
|
||||
|
||||
import (
|
||||
"context"
|
||||
"net/http"
|
||||
|
||||
"github.com/google/uuid"
|
||||
|
||||
"gitea.privcloud.tech/mtusi2026/internal/pkg/rest/headers"
|
||||
)
|
||||
|
||||
func RequestIDMiddleware() Middleware {
|
||||
return func(next http.Handler) http.Handler {
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
ctx := r.Context()
|
||||
requestID := uuid.New()
|
||||
w.Header().Set(headers.HeaderRequestID, requestID.String())
|
||||
ctx = context.WithValue(ctx, headers.HeaderRequestID, requestID)
|
||||
next.ServeHTTP(w, r.WithContext(ctx))
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,131 @@
|
||||
package router
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
|
||||
"github.com/go-chi/chi/v5"
|
||||
|
||||
"gitea.privcloud.tech/mtusi2026/internal/pkg/rest/middleware"
|
||||
)
|
||||
|
||||
type Router interface {
|
||||
Private(method, pattern string, handler http.HandlerFunc, mw ...func(http.Handler) http.Handler)
|
||||
Public(method, pattern string, handler http.HandlerFunc, mw ...func(http.Handler) http.Handler)
|
||||
Admin(method, pattern string, handler http.HandlerFunc, mw ...func(http.Handler) http.Handler)
|
||||
ServeHTTP(w http.ResponseWriter, r *http.Request)
|
||||
With(mw ...func(http.Handler) http.Handler) Router
|
||||
Use(mw ...func(http.Handler) http.Handler) Router
|
||||
Handle(pattern string, handler http.Handler)
|
||||
Get(pattern string, handler http.HandlerFunc)
|
||||
Head(pattern string, handler http.HandlerFunc)
|
||||
Options(pattern string, handler http.HandlerFunc)
|
||||
Post(pattern string, handler http.HandlerFunc)
|
||||
Put(pattern string, handler http.HandlerFunc)
|
||||
Patch(pattern string, handler http.HandlerFunc)
|
||||
Delete(pattern string, handler http.HandlerFunc)
|
||||
Connect(pattern string, handler http.HandlerFunc)
|
||||
Trace(pattern string, handler http.HandlerFunc)
|
||||
}
|
||||
|
||||
type router struct {
|
||||
r chi.Router
|
||||
jwtMw middleware.AuthMiddleware
|
||||
}
|
||||
|
||||
func New(jwtMw middleware.AuthMiddleware, mw ...middleware.Middleware) Router {
|
||||
r := chi.NewRouter()
|
||||
r.Use(mw...)
|
||||
return &router{
|
||||
r: r,
|
||||
jwtMw: jwtMw,
|
||||
}
|
||||
}
|
||||
|
||||
func (c *router) Group(pattern string) Router {
|
||||
sub := &router{
|
||||
r: chi.NewRouter(),
|
||||
jwtMw: c.jwtMw,
|
||||
}
|
||||
c.r.Mount(pattern, sub.r)
|
||||
return sub
|
||||
}
|
||||
|
||||
func (c *router) Public(method, pattern string, handler http.HandlerFunc, mw ...func(http.Handler) http.Handler) {
|
||||
next := c.applyMiddlewares(handler, mw...)
|
||||
c.r.MethodFunc(method, pattern, next.ServeHTTP)
|
||||
}
|
||||
|
||||
func (c *router) Private(method, pattern string, handler http.HandlerFunc, mw ...func(http.Handler) http.Handler) {
|
||||
next := c.applyMiddlewares(handler, mw...)
|
||||
c.r.MethodFunc(method, pattern, (c.jwtMw.WithPrivateAccess(next)).ServeHTTP)
|
||||
}
|
||||
|
||||
func (c *router) Admin(method, pattern string, handler http.HandlerFunc, mw ...func(http.Handler) http.Handler) {
|
||||
next := c.applyMiddlewares(handler, mw...)
|
||||
c.r.MethodFunc(method, pattern, (c.jwtMw.WithAdminAccess(next)).ServeHTTP)
|
||||
}
|
||||
|
||||
func (c *router) ServeHTTP(w http.ResponseWriter, r *http.Request) {
|
||||
c.r.ServeHTTP(w, r)
|
||||
}
|
||||
|
||||
func (c *router) With(mw ...func(http.Handler) http.Handler) Router {
|
||||
sub := &router{
|
||||
r: c.r.With(mw...),
|
||||
jwtMw: c.jwtMw,
|
||||
}
|
||||
return sub
|
||||
}
|
||||
|
||||
func (c *router) Use(mw ...func(http.Handler) http.Handler) Router {
|
||||
c.r.Use(mw...)
|
||||
return c
|
||||
}
|
||||
|
||||
func (c *router) Handle(pattern string, handler http.Handler) {
|
||||
c.r.Handle(pattern, handler)
|
||||
}
|
||||
|
||||
func (c *router) Get(pattern string, handler http.HandlerFunc) {
|
||||
c.r.Get(pattern, handler)
|
||||
}
|
||||
|
||||
func (c *router) Head(pattern string, handler http.HandlerFunc) {
|
||||
c.r.Head(pattern, handler)
|
||||
}
|
||||
|
||||
func (c *router) Options(pattern string, handler http.HandlerFunc) {
|
||||
c.r.Options(pattern, handler)
|
||||
}
|
||||
|
||||
func (c *router) Post(pattern string, handler http.HandlerFunc) {
|
||||
c.r.Post(pattern, handler)
|
||||
}
|
||||
|
||||
func (c *router) Put(pattern string, handler http.HandlerFunc) {
|
||||
c.r.Put(pattern, handler)
|
||||
}
|
||||
|
||||
func (c *router) Patch(pattern string, handler http.HandlerFunc) {
|
||||
c.r.Patch(pattern, handler)
|
||||
}
|
||||
|
||||
func (c *router) Delete(pattern string, handler http.HandlerFunc) {
|
||||
c.r.Delete(pattern, handler)
|
||||
}
|
||||
|
||||
func (c *router) Connect(pattern string, handler http.HandlerFunc) {
|
||||
c.r.Connect(pattern, handler)
|
||||
}
|
||||
|
||||
func (c *router) Trace(pattern string, handler http.HandlerFunc) {
|
||||
c.r.Trace(pattern, handler)
|
||||
}
|
||||
|
||||
func (c *router) applyMiddlewares(handler http.HandlerFunc, mw ...func(http.Handler) http.Handler) http.Handler {
|
||||
next := http.Handler(handler)
|
||||
for _, mwFunc := range mw {
|
||||
next = mwFunc(next)
|
||||
}
|
||||
return next
|
||||
}
|
||||
@@ -0,0 +1,82 @@
|
||||
package authprovider
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"strings"
|
||||
|
||||
"gitea.privcloud.tech/mtusi2026/internal/pkg/types"
|
||||
)
|
||||
|
||||
type Type string
|
||||
|
||||
const (
|
||||
TypeUndefined Type = "undefined"
|
||||
TypePassword Type = "password"
|
||||
TypeEmail Type = "email"
|
||||
TypePhone Type = "phone"
|
||||
TypeGoogle Type = "google"
|
||||
TypeTelegram Type = "telegram"
|
||||
)
|
||||
|
||||
var allowedTypes = map[Type]struct{}{
|
||||
TypePassword: {},
|
||||
TypeEmail: {},
|
||||
TypePhone: {},
|
||||
TypeGoogle: {},
|
||||
TypeTelegram: {},
|
||||
}
|
||||
|
||||
func ParseType(value string) Type {
|
||||
t := Type(strings.ToLower(value))
|
||||
if !t.IsValid() {
|
||||
return TypeUndefined
|
||||
}
|
||||
return t
|
||||
}
|
||||
|
||||
func ParseAndValidateType(value string) (Type, error) {
|
||||
parsed := ParseType(value)
|
||||
if _, ok := allowedTypes[parsed]; ok {
|
||||
return parsed, nil
|
||||
}
|
||||
return TypeUndefined, types.ErrUnsupportedOTPStatus
|
||||
}
|
||||
|
||||
func (t Type) String() string {
|
||||
return string(t)
|
||||
}
|
||||
|
||||
func (t Type) Validate() error {
|
||||
if _, ok := allowedTypes[t]; ok {
|
||||
return nil
|
||||
}
|
||||
return types.ErrUnsupportedAuthProviderType
|
||||
}
|
||||
|
||||
func (t Type) IsValid() bool {
|
||||
_, ok := allowedTypes[t]
|
||||
return ok
|
||||
}
|
||||
|
||||
func (t Type) MarshalJSON() ([]byte, error) {
|
||||
if err := t.Validate(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return json.Marshal(t.String())
|
||||
}
|
||||
|
||||
func (t *Type) UnmarshalJSON(data []byte) error {
|
||||
if t == nil {
|
||||
return types.ErrUnmarshalAuthProviderTypeIntoNilPointer
|
||||
}
|
||||
var value string
|
||||
if err := json.Unmarshal(data, &value); err != nil {
|
||||
return err
|
||||
}
|
||||
parsed := ParseType(value)
|
||||
if err := parsed.Validate(); err != nil {
|
||||
return err
|
||||
}
|
||||
*t = parsed
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,77 @@
|
||||
package environment
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"strings"
|
||||
|
||||
"gitea.privcloud.tech/mtusi2026/internal/pkg/types"
|
||||
)
|
||||
|
||||
type ApplicationEnvironment string
|
||||
|
||||
const (
|
||||
ApplicationEnvironmentUndefined ApplicationEnvironment = "undefined"
|
||||
ApplicationEnvironmentDev ApplicationEnvironment = "dev"
|
||||
ApplicationEnvironmentProd ApplicationEnvironment = "prod"
|
||||
)
|
||||
|
||||
var allowedEnvironments = map[ApplicationEnvironment]struct{}{
|
||||
ApplicationEnvironmentUndefined: {},
|
||||
ApplicationEnvironmentDev: {},
|
||||
ApplicationEnvironmentProd: {},
|
||||
}
|
||||
|
||||
func ParseEnvironment(value string) ApplicationEnvironment {
|
||||
s := ApplicationEnvironment(strings.ToLower(value))
|
||||
if !s.IsValid() {
|
||||
return ApplicationEnvironmentUndefined
|
||||
}
|
||||
return s
|
||||
}
|
||||
|
||||
func ParseAndValidateEnvironment(status string) (ApplicationEnvironment, error) {
|
||||
parsed := ParseEnvironment(status)
|
||||
if _, ok := allowedEnvironments[parsed]; ok {
|
||||
return parsed, nil
|
||||
}
|
||||
return ApplicationEnvironmentUndefined, types.ErrUnsupportedApplicationEnvironment
|
||||
}
|
||||
|
||||
func (t ApplicationEnvironment) String() string {
|
||||
return string(t)
|
||||
}
|
||||
|
||||
func (t ApplicationEnvironment) Validate() error {
|
||||
if _, ok := allowedEnvironments[t]; ok {
|
||||
return nil
|
||||
}
|
||||
return types.ErrUnsupportedApplicationEnvironment
|
||||
}
|
||||
|
||||
func (t ApplicationEnvironment) IsValid() bool {
|
||||
_, ok := allowedEnvironments[t]
|
||||
return ok
|
||||
}
|
||||
|
||||
func (t ApplicationEnvironment) MarshalJSON() ([]byte, error) {
|
||||
if err := t.Validate(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return json.Marshal(t.String())
|
||||
}
|
||||
|
||||
func (t *ApplicationEnvironment) UnmarshalJSON(data []byte) error {
|
||||
if t == nil {
|
||||
return types.ErrUnmarshalApplicationEnvironmentIntoNilPointer
|
||||
}
|
||||
var value string
|
||||
if err := json.Unmarshal(data, &value); err != nil {
|
||||
return err
|
||||
}
|
||||
parsed := ParseEnvironment(value)
|
||||
if err := parsed.Validate(); err != nil {
|
||||
return err
|
||||
}
|
||||
*t = parsed
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
package types
|
||||
|
||||
import "errors"
|
||||
|
||||
var (
|
||||
ErrUnsupportedRole = errors.New("unsupported role")
|
||||
ErrUnsupportedOTPType = errors.New("unsupported OTP type")
|
||||
ErrUnsupportedAuthProviderType = errors.New("unsupported auth provider type")
|
||||
ErrUnsupportedContactType = errors.New("unsupported contact type")
|
||||
ErrUnsupportedOTPStatus = errors.New("unsupported OTP status")
|
||||
ErrUnsupportedOTPResult = errors.New("unsupported OTP result")
|
||||
ErrUnsupportedFormStatus = errors.New("unsupported form status")
|
||||
ErrUnsupportedAuthIdentityStatus = errors.New("unsupported auth identity status")
|
||||
ErrUnsupportedApplicationEnvironment = errors.New("unsupported application environment")
|
||||
|
||||
ErrUnmarshalRoleIntoNilPointer = errors.New("unmarshal role into nil pointer")
|
||||
ErrUnmarshalOTPTypeIntoNilPointer = errors.New("unmarshal OTP type into nil pointer")
|
||||
ErrUnmarshalAuthProviderTypeIntoNilPointer = errors.New("unmarshal auth provider into nil pointer")
|
||||
ErrUnmarshalContactTypeIntoNilPointer = errors.New("unmarshal contact into nil pointer")
|
||||
ErrUnmarshalOTPStatusIntoNilPointer = errors.New("unmarshal OTP status into nil pointer")
|
||||
ErrUnmarshalOTPResultIntoNilPointer = errors.New("unmarshal OTP result into nil pointer")
|
||||
ErrUnmarshalFormStatusIntoNilPointer = errors.New("unmarshal form status into nil pointer")
|
||||
ErrUnmarshalAuthIdentityStatusIntoNilPointer = errors.New("unmarshal auth identity status into nil pointer")
|
||||
ErrUnmarshalApplicationEnvironmentIntoNilPointer = errors.New("unmarshal application environment into nil pointer")
|
||||
)
|
||||
@@ -0,0 +1,105 @@
|
||||
package role
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"strings"
|
||||
|
||||
"gitea.privcloud.tech/mtusi2026/internal/pkg/types"
|
||||
)
|
||||
|
||||
type Role string
|
||||
|
||||
const (
|
||||
Undefined Role = "undefined"
|
||||
User Role = "user"
|
||||
Doctor Role = "doctor"
|
||||
Manager Role = "manager"
|
||||
Admin Role = "admin"
|
||||
)
|
||||
|
||||
var allowedRoles = map[Role]struct{}{
|
||||
User: {},
|
||||
Doctor: {},
|
||||
Manager: {},
|
||||
Admin: {},
|
||||
}
|
||||
|
||||
func ParseRole(s string) Role {
|
||||
r := Role(strings.ToLower(s))
|
||||
if !r.IsValid() {
|
||||
return Undefined
|
||||
}
|
||||
return r
|
||||
}
|
||||
|
||||
func ParseAndValidateRole(s string) (Role, error) {
|
||||
parsed := ParseRole(s)
|
||||
if _, ok := allowedRoles[parsed]; ok {
|
||||
return parsed, nil
|
||||
}
|
||||
return Undefined, types.ErrUnsupportedRole
|
||||
}
|
||||
|
||||
func (t Role) String() string {
|
||||
return string(t)
|
||||
}
|
||||
|
||||
func (t Role) Validate() error {
|
||||
if _, ok := allowedRoles[t]; ok {
|
||||
return nil
|
||||
}
|
||||
return types.ErrUnsupportedRole
|
||||
}
|
||||
|
||||
func (t Role) IsValid() bool {
|
||||
_, ok := allowedRoles[t]
|
||||
return ok
|
||||
}
|
||||
|
||||
func (t Role) MarshalJSON() ([]byte, error) {
|
||||
if err := t.Validate(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return json.Marshal(t.String())
|
||||
}
|
||||
|
||||
func (t *Role) UnmarshalJSON(data []byte) error {
|
||||
if t == nil {
|
||||
return types.ErrUnmarshalRoleIntoNilPointer
|
||||
}
|
||||
var value string
|
||||
if err := json.Unmarshal(data, &value); err != nil {
|
||||
return err
|
||||
}
|
||||
parsed := ParseRole(value)
|
||||
if err := parsed.Validate(); err != nil {
|
||||
return err
|
||||
}
|
||||
*t = parsed
|
||||
return nil
|
||||
}
|
||||
|
||||
func (t Role) IsAdmin() bool {
|
||||
return t == Admin
|
||||
}
|
||||
|
||||
func (t Role) IsManager() bool {
|
||||
return t == Manager
|
||||
}
|
||||
|
||||
func (t Role) IsDoctor() bool {
|
||||
return t == Doctor
|
||||
}
|
||||
|
||||
func (t Role) IsUser() bool {
|
||||
return t == User
|
||||
}
|
||||
|
||||
func (t Role) IsPrivileged() bool {
|
||||
switch t {
|
||||
case Doctor, Manager, Admin:
|
||||
return true
|
||||
default:
|
||||
return false
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
package validator
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"github.com/go-playground/validator/v10"
|
||||
)
|
||||
|
||||
type TagKey string
|
||||
|
||||
type ValidatorImpl struct {
|
||||
validator *validator.Validate
|
||||
}
|
||||
|
||||
func NewValidatorImpl() *ValidatorImpl {
|
||||
return &ValidatorImpl{validator: validator.New()}
|
||||
}
|
||||
|
||||
func (v *ValidatorImpl) Register(tag TagKey, fn validator.Func, callValidationEvenIfNull ...bool) error {
|
||||
return v.validator.RegisterValidation(string(tag), fn, callValidationEvenIfNull...)
|
||||
}
|
||||
|
||||
func (v *ValidatorImpl) ValidateCtx(ctx context.Context, value any) error {
|
||||
return v.validator.StructCtx(ctx, value)
|
||||
}
|
||||
|
||||
func (v *ValidatorImpl) Validate(value any) error {
|
||||
return v.validator.Struct(value)
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
package auth
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"gitea.privcloud.tech/mtusi2026/internal/dto"
|
||||
)
|
||||
|
||||
type API interface {
|
||||
Login(ctx context.Context, req dto.Login) (*dto.LoginResult, error)
|
||||
VerifyAccessToken(ctx context.Context, req dto.Token) (*dto.UserDataInToken, error)
|
||||
VerifySession(ctx context.Context, token dto.Token) (*dto.UserDataInToken, error)
|
||||
RefreshTokens(ctx context.Context, req dto.RefreshToken) (*dto.Tokens, error)
|
||||
Logout(ctx context.Context, req dto.RefreshToken) error
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
package auth
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"github.com/google/uuid"
|
||||
"github.com/jackc/pgx/v5"
|
||||
|
||||
"gitea.privcloud.tech/mtusi2026/internal/dto"
|
||||
)
|
||||
|
||||
type userRepo interface {
|
||||
GetCredentialsByUsername(ctx context.Context, username string) (*dto.UserCredentials, error)
|
||||
}
|
||||
|
||||
type refreshTokensRepo interface {
|
||||
GetByID(ctx context.Context, id uuid.UUID) (*dto.StoredRefreshToken, error)
|
||||
GetByIDForUpdateTx(ctx context.Context, tx pgx.Tx, id uuid.UUID) (*dto.StoredRefreshToken, error)
|
||||
CreateTx(ctx context.Context, tx pgx.Tx, req dto.StoredRefreshToken) error
|
||||
RevokeTx(ctx context.Context, tx pgx.Tx, req dto.RevokeRefreshToken) error
|
||||
}
|
||||
@@ -0,0 +1,267 @@
|
||||
package auth
|
||||
|
||||
import (
|
||||
"context"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
"github.com/jackc/pgx/v5"
|
||||
|
||||
"gitea.privcloud.tech/mtusi2026/internal/dto"
|
||||
"gitea.privcloud.tech/mtusi2026/internal/pkg/apperr"
|
||||
"gitea.privcloud.tech/mtusi2026/internal/pkg/auth/jwtprovider"
|
||||
"gitea.privcloud.tech/mtusi2026/internal/pkg/encrypting"
|
||||
"gitea.privcloud.tech/mtusi2026/internal/pkg/postgres/txmanager"
|
||||
"gitea.privcloud.tech/mtusi2026/internal/pkg/types/role"
|
||||
)
|
||||
|
||||
var _ API = (*Auth)(nil)
|
||||
|
||||
type Auth struct {
|
||||
jwt jwtprovider.Provider
|
||||
tm *txmanager.TransactionManager
|
||||
encryptor encrypting.Encryptor
|
||||
|
||||
usersRepo userRepo
|
||||
refreshTokensRepo refreshTokensRepo
|
||||
}
|
||||
|
||||
func New(
|
||||
jwt jwtprovider.Provider,
|
||||
tm *txmanager.TransactionManager,
|
||||
encryptor encrypting.Encryptor,
|
||||
usersRepo userRepo,
|
||||
refreshTokensRepo refreshTokensRepo,
|
||||
) *Auth {
|
||||
return &Auth{
|
||||
jwt: jwt,
|
||||
tm: tm,
|
||||
encryptor: encryptor,
|
||||
usersRepo: usersRepo,
|
||||
refreshTokensRepo: refreshTokensRepo,
|
||||
}
|
||||
}
|
||||
|
||||
func (a *Auth) Login(ctx context.Context, req dto.Login) (*dto.LoginResult, error) {
|
||||
if req.Username == "" || req.Password == "" {
|
||||
return nil, apperr.New(apperr.CodeUnauthorized, "invalid credentials")
|
||||
}
|
||||
|
||||
credentials, err := a.usersRepo.GetCredentialsByUsername(ctx, req.Username)
|
||||
if err != nil {
|
||||
if apperr.CodeFromError(err) == apperr.CodeNotFound {
|
||||
return nil, apperr.New(apperr.CodeUnauthorized, "invalid credentials")
|
||||
}
|
||||
return nil, err
|
||||
}
|
||||
if err = a.encryptor.CompareHashAndSecretUsingArgon2id(ctx, credentials.PasswordHash, req.Password); err != nil {
|
||||
if ctx.Err() != nil {
|
||||
return nil, ctx.Err()
|
||||
}
|
||||
return nil, apperr.New(apperr.CodeUnauthorized, "invalid credentials")
|
||||
}
|
||||
|
||||
var (
|
||||
tokens *dto.Tokens
|
||||
data *dto.UserDataInToken
|
||||
)
|
||||
err = a.tm.RunInTransaction(ctx, nil, func(tx pgx.Tx) error {
|
||||
tokens, err = a.jwt.CreateRefreshAndAccessTokensForUser(credentials.User.ID, role.User)
|
||||
if err != nil {
|
||||
return apperr.Wrap(err, apperr.CodeInternal, "failed to generate tokens")
|
||||
}
|
||||
data, err = a.verifyToken(tokens.RefreshToken.Token(), false)
|
||||
if err != nil {
|
||||
return apperr.Wrap(err, apperr.CodeInternal, "failed to validate generated refresh token")
|
||||
}
|
||||
var hash string
|
||||
hash, err = a.encryptor.EncryptSecretUsingSum256(ctx, tokens.RefreshToken.Payload)
|
||||
if err != nil {
|
||||
return apperr.Wrap(err, apperr.CodeInternal, "failed to hash refresh token")
|
||||
}
|
||||
stored := dto.StoredRefreshToken{
|
||||
ID: data.TokenID,
|
||||
UserID: data.UserID,
|
||||
TokenHash: hash,
|
||||
Role: data.Role,
|
||||
ExpiresAt: data.ExpiresAt,
|
||||
CreatedAt: data.IssuedAt,
|
||||
}
|
||||
if err = a.refreshTokensRepo.CreateTx(ctx, tx, stored); err != nil {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return &dto.LoginResult{
|
||||
ExpiresAt: data.ExpiresAt,
|
||||
TokenType: "Bearer",
|
||||
User: credentials.User,
|
||||
Tokens: *tokens,
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (a *Auth) VerifyAccessToken(ctx context.Context, req dto.Token) (*dto.UserDataInToken, error) {
|
||||
if err := ctx.Err(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return a.verifyToken(&req, true)
|
||||
}
|
||||
|
||||
func (a *Auth) VerifySession(ctx context.Context, token dto.Token) (*dto.UserDataInToken, error) {
|
||||
if err := ctx.Err(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
data, err := a.verifyTokenClaims(&token)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if data.IsAccess {
|
||||
return nil, apperr.New(apperr.CodeUnauthorized, "invalid session token")
|
||||
}
|
||||
|
||||
stored, err := a.refreshTokensRepo.GetByID(ctx, data.TokenID)
|
||||
if err != nil {
|
||||
if apperr.CodeFromError(err) == apperr.CodeNotFound {
|
||||
return nil, apperr.New(apperr.CodeUnauthorized, "invalid session")
|
||||
}
|
||||
return nil, err
|
||||
}
|
||||
if err = a.validateStoredSession(ctx, token, data, stored); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return data, nil
|
||||
}
|
||||
|
||||
func (a *Auth) Logout(ctx context.Context, req dto.RefreshToken) error {
|
||||
data, err := a.verifyToken(req.Token(), false)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
return a.tm.RunInTransaction(ctx, nil, func(tx pgx.Tx) error {
|
||||
stored, err := a.activeRefreshTokenTx(ctx, tx, req, data)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return a.refreshTokensRepo.RevokeTx(ctx, tx, dto.RevokeRefreshToken{
|
||||
ID: stored.ID,
|
||||
RevokedAt: time.Now(),
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
func (a *Auth) RefreshTokens(ctx context.Context, req dto.RefreshToken) (*dto.Tokens, error) {
|
||||
data, err := a.verifyToken(req.Token(), false)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
var tokens *dto.Tokens
|
||||
err = a.tm.RunInTransaction(ctx, nil, func(tx pgx.Tx) error {
|
||||
stored, err := a.activeRefreshTokenTx(ctx, tx, req, data)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if err = a.refreshTokensRepo.RevokeTx(ctx, tx, dto.RevokeRefreshToken{
|
||||
ID: stored.ID,
|
||||
RevokedAt: time.Now(),
|
||||
}); err != nil {
|
||||
return err
|
||||
}
|
||||
tokens, err = a.createTokensTx(ctx, tx, stored.UserID, stored)
|
||||
return err
|
||||
})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return tokens, nil
|
||||
}
|
||||
|
||||
func (a *Auth) verifyToken(token *dto.Token, isAccess bool) (*dto.UserDataInToken, error) {
|
||||
data, err := a.verifyTokenClaims(token)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if data.IsAccess != isAccess || data.Role != role.User {
|
||||
return nil, apperr.New(apperr.CodeUnauthorized, "invalid token")
|
||||
}
|
||||
return data, nil
|
||||
}
|
||||
|
||||
func (a *Auth) verifyTokenClaims(token *dto.Token) (*dto.UserDataInToken, error) {
|
||||
data, err := a.jwt.ParseVerified(token)
|
||||
if err != nil {
|
||||
return nil, apperr.Wrap(err, apperr.CodeUnauthorized, "invalid token")
|
||||
}
|
||||
if err = data.Validate(); err != nil {
|
||||
return nil, apperr.Wrap(err, apperr.CodeUnauthorized, "invalid token claims")
|
||||
}
|
||||
now := time.Now()
|
||||
if data.IssuedAt.After(now) || !data.ExpiresAt.After(now) {
|
||||
return nil, apperr.New(apperr.CodeUnauthorized, "invalid token")
|
||||
}
|
||||
return data, nil
|
||||
}
|
||||
|
||||
func (a *Auth) activeRefreshTokenTx(ctx context.Context, tx pgx.Tx, token dto.RefreshToken, data *dto.UserDataInToken) (*dto.StoredRefreshToken, error) {
|
||||
stored, err := a.refreshTokensRepo.GetByIDForUpdateTx(ctx, tx, data.TokenID)
|
||||
if err != nil {
|
||||
if apperr.CodeFromError(err) == apperr.CodeNotFound {
|
||||
return nil, apperr.New(apperr.CodeUnauthorized, "invalid refresh token")
|
||||
}
|
||||
return nil, err
|
||||
}
|
||||
|
||||
// Recheck expiry after acquiring the row lock: a concurrent rotation may have held it.
|
||||
if err = a.validateStoredSession(ctx, dto.Token(token), data, stored); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return stored, nil
|
||||
}
|
||||
|
||||
func (a *Auth) validateStoredSession(ctx context.Context, token dto.Token, data *dto.UserDataInToken, stored *dto.StoredRefreshToken) error {
|
||||
now := time.Now()
|
||||
if stored.RevokedAt != nil || !stored.ExpiresAt.After(now) || !data.ExpiresAt.After(now) ||
|
||||
stored.UserID != data.UserID || stored.Role != data.Role {
|
||||
return apperr.New(apperr.CodeUnauthorized, "invalid session")
|
||||
}
|
||||
if err := a.encryptor.CompareHashAndSecretUsingSum256(ctx, stored.TokenHash, token.Payload); err != nil {
|
||||
return apperr.New(apperr.CodeUnauthorized, "invalid session")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (a *Auth) createTokensTx(ctx context.Context, tx pgx.Tx, userID uuid.UUID, previous *dto.StoredRefreshToken) (*dto.Tokens, error) {
|
||||
tokens, err := a.jwt.CreateRefreshAndAccessTokensForUser(userID, role.User)
|
||||
if err != nil {
|
||||
return nil, apperr.Wrap(err, apperr.CodeInternal, "failed to generate tokens")
|
||||
}
|
||||
data, err := a.verifyToken(tokens.RefreshToken.Token(), false)
|
||||
if err != nil {
|
||||
return nil, apperr.Wrap(err, apperr.CodeInternal, "failed to validate generated refresh token")
|
||||
}
|
||||
hash, err := a.encryptor.EncryptSecretUsingSum256(ctx, tokens.RefreshToken.Payload)
|
||||
if err != nil {
|
||||
return nil, apperr.Wrap(err, apperr.CodeInternal, "failed to hash refresh token")
|
||||
}
|
||||
stored := dto.StoredRefreshToken{
|
||||
ID: data.TokenID,
|
||||
UserID: data.UserID,
|
||||
TokenHash: hash,
|
||||
Role: data.Role,
|
||||
ExpiresAt: data.ExpiresAt,
|
||||
CreatedAt: data.IssuedAt,
|
||||
}
|
||||
if previous != nil {
|
||||
stored.UserAgent = previous.UserAgent
|
||||
stored.IPAddress = previous.IPAddress
|
||||
}
|
||||
if err = a.refreshTokensRepo.CreateTx(ctx, tx, stored); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return tokens, nil
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
package chat
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"gitea.privcloud.tech/mtusi2026/internal/dto"
|
||||
)
|
||||
|
||||
type API interface {
|
||||
CreateChat(ctx context.Context, req dto.CreateChat) (*dto.Chat, error)
|
||||
GetForMember(ctx context.Context, req dto.ChatMember) (*dto.Chat, error)
|
||||
ListForMember(ctx context.Context, req dto.ChatFilters) (*dto.Page[dto.Chat], error)
|
||||
CreateMessage(ctx context.Context, req dto.CreateMessage) (*dto.Message, error)
|
||||
ListForChat(ctx context.Context, req dto.MessageFilters) (*dto.Page[dto.Message], error)
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
package chat
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"github.com/google/uuid"
|
||||
"github.com/jackc/pgx/v5"
|
||||
|
||||
"gitea.privcloud.tech/mtusi2026/internal/dto"
|
||||
)
|
||||
|
||||
type chatsRepo interface {
|
||||
CreateTx(ctx context.Context, tx pgx.Tx, req dto.Chat) error
|
||||
GetForMember(ctx context.Context, req dto.ChatMember) (*dto.Chat, error)
|
||||
ListForMember(ctx context.Context, userID uuid.UUID, page dto.PageQuery) ([]dto.Chat, error)
|
||||
}
|
||||
|
||||
type messagesRepo interface {
|
||||
Create(ctx context.Context, req dto.Message) error
|
||||
GetByIDForChat(ctx context.Context, chatID, messageID uuid.UUID) (*dto.Message, error)
|
||||
ListForChat(ctx context.Context, chatID uuid.UUID, page dto.PageQuery) ([]dto.Message, error)
|
||||
}
|
||||
|
||||
type chatsCache interface {
|
||||
Create(ctx context.Context, req dto.Chat) error
|
||||
Get(ctx context.Context, chatID uuid.UUID) (*dto.Chat, error)
|
||||
}
|
||||
@@ -0,0 +1,242 @@
|
||||
package chat
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"errors"
|
||||
"log/slog"
|
||||
"slices"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
"github.com/jackc/pgx/v5"
|
||||
"github.com/redis/go-redis/v9"
|
||||
"golang.org/x/sync/singleflight"
|
||||
|
||||
"gitea.privcloud.tech/mtusi2026/internal/dto"
|
||||
"gitea.privcloud.tech/mtusi2026/internal/pkg/apperr"
|
||||
"gitea.privcloud.tech/mtusi2026/internal/pkg/postgres/txmanager"
|
||||
)
|
||||
|
||||
var _ API = (*Chat)(nil)
|
||||
|
||||
const chatLoadTimeout = 2 * time.Second
|
||||
|
||||
type Chat struct {
|
||||
tm *txmanager.TransactionManager
|
||||
chatsRepo chatsRepo
|
||||
messagesRepo messagesRepo
|
||||
chatsCache chatsCache
|
||||
loads singleflight.Group
|
||||
}
|
||||
|
||||
func New(tm *txmanager.TransactionManager, chatsRepo chatsRepo, messagesRepo messagesRepo, chatsCache chatsCache) *Chat {
|
||||
return &Chat{
|
||||
tm: tm,
|
||||
chatsRepo: chatsRepo,
|
||||
messagesRepo: messagesRepo,
|
||||
chatsCache: chatsCache,
|
||||
}
|
||||
}
|
||||
|
||||
func (c *Chat) CreateChat(ctx context.Context, req dto.CreateChat) (*dto.Chat, error) {
|
||||
seen := make(map[uuid.UUID]struct{}, len(req.MemberIDs))
|
||||
for _, id := range req.MemberIDs {
|
||||
if id == uuid.Nil {
|
||||
return nil, apperr.New(apperr.CodeBadRequest, "invalid chat member")
|
||||
}
|
||||
if _, exists := seen[id]; exists {
|
||||
return nil, apperr.New(apperr.CodeBadRequest, "duplicate chat member")
|
||||
}
|
||||
seen[id] = struct{}{}
|
||||
}
|
||||
|
||||
if _, included := seen[req.CreatorID]; !included {
|
||||
return nil, apperr.New(apperr.CodeBadRequest, "creator must be a chat member")
|
||||
}
|
||||
|
||||
members := slices.Clone(req.MemberIDs)
|
||||
slices.SortFunc(members, func(a, b uuid.UUID) int {
|
||||
return bytes.Compare(a[:], b[:])
|
||||
})
|
||||
chat := dto.Chat{
|
||||
ID: uuid.New(),
|
||||
Title: req.Title,
|
||||
MemberIDs: members,
|
||||
CreatedAt: time.Now().Truncate(time.Microsecond),
|
||||
}
|
||||
|
||||
if err := c.tm.RunInTransaction(ctx, nil, func(tx pgx.Tx) error {
|
||||
return c.chatsRepo.CreateTx(ctx, tx, chat)
|
||||
}); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return &chat, nil
|
||||
}
|
||||
|
||||
func (c *Chat) GetForMember(ctx context.Context, req dto.ChatMember) (*dto.Chat, error) {
|
||||
if err := ctx.Err(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if chat, err := c.cachedChat(ctx, req.ChatID); err == nil {
|
||||
return chatForMember(chat, req.UserID)
|
||||
}
|
||||
|
||||
// Repository results depend on membership: never share a user's 404 with
|
||||
// another user requesting the same chat.
|
||||
key := req.ChatID.String() + ":" + req.UserID.String()
|
||||
result := c.loads.DoChan(key, func() (any, error) {
|
||||
// One client disconnecting must not cancel the other clients' load.
|
||||
loadCtx, cancel := context.WithTimeout(context.WithoutCancel(ctx), chatLoadTimeout)
|
||||
defer cancel()
|
||||
|
||||
// A previous load may have populated Redis after our initial miss.
|
||||
if chat, err := c.cachedChat(loadCtx, req.ChatID); err == nil {
|
||||
return chatForMember(chat, req.UserID)
|
||||
}
|
||||
|
||||
slog.Info("chat_db_lookup", "chat_id", req.ChatID)
|
||||
chat, err := c.chatsRepo.GetForMember(loadCtx, req)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if err = c.chatsCache.Create(loadCtx, *chat); err != nil {
|
||||
slog.Warn("failed to cache chat", "chat_id", req.ChatID, "error", err)
|
||||
}
|
||||
return chat, nil
|
||||
})
|
||||
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return nil, ctx.Err()
|
||||
case loaded := <-result:
|
||||
if err := ctx.Err(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if loaded.Err != nil {
|
||||
return nil, loaded.Err
|
||||
}
|
||||
return chatForMember(loaded.Val.(*dto.Chat), req.UserID)
|
||||
}
|
||||
}
|
||||
|
||||
func (c *Chat) cachedChat(ctx context.Context, chatID uuid.UUID) (*dto.Chat, error) {
|
||||
chat, err := c.chatsCache.Get(ctx, chatID)
|
||||
switch {
|
||||
case err == nil:
|
||||
slog.Info("chat_cache_hit", "chat_id", chatID)
|
||||
case errors.Is(err, redis.Nil):
|
||||
slog.Info("chat_cache_miss", "chat_id", chatID)
|
||||
default:
|
||||
slog.Warn("chat_cache_read_error", "chat_id", chatID, "error", err)
|
||||
}
|
||||
return chat, err
|
||||
}
|
||||
|
||||
func chatForMember(chat *dto.Chat, userID uuid.UUID) (*dto.Chat, error) {
|
||||
if !slices.Contains(chat.MemberIDs, userID) {
|
||||
return nil, apperr.New(apperr.CodeNotFound, "chat not found")
|
||||
}
|
||||
return chat, nil
|
||||
}
|
||||
|
||||
func (c *Chat) ListForMember(ctx context.Context, req dto.ChatFilters) (*dto.Page[dto.Chat], error) {
|
||||
limit, err := pageLimit(req.Limit)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
query := dto.PageQuery{Limit: limit + 1}
|
||||
if req.AfterID != nil {
|
||||
cursor, err := c.GetForMember(ctx, dto.ChatMember{UserID: req.UserID, ChatID: *req.AfterID})
|
||||
if err != nil {
|
||||
return nil, cursorError(err)
|
||||
}
|
||||
query.After = &dto.PagePosition{CreatedAt: cursor.CreatedAt, ID: cursor.ID}
|
||||
}
|
||||
|
||||
items, err := c.chatsRepo.ListForMember(ctx, req.UserID, query)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return makePage(items, limit, func(chat dto.Chat) uuid.UUID { return chat.ID }), nil
|
||||
}
|
||||
|
||||
func (c *Chat) CreateMessage(ctx context.Context, req dto.CreateMessage) (*dto.Message, error) {
|
||||
if _, err := c.GetForMember(ctx, dto.ChatMember{UserID: req.SenderID, ChatID: req.ChatID}); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
message := dto.Message{
|
||||
ID: uuid.New(),
|
||||
ChatID: req.ChatID,
|
||||
SenderID: req.SenderID,
|
||||
Text: req.Text,
|
||||
CreatedAt: time.Now().Truncate(time.Microsecond),
|
||||
}
|
||||
if err := c.messagesRepo.Create(ctx, message); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return &message, nil
|
||||
}
|
||||
|
||||
func (c *Chat) ListForChat(ctx context.Context, req dto.MessageFilters) (*dto.Page[dto.Message], error) {
|
||||
if _, err := c.GetForMember(ctx, dto.ChatMember{UserID: req.UserID, ChatID: req.ChatID}); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
limit, err := pageLimit(req.Limit)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
query := dto.PageQuery{Limit: limit + 1}
|
||||
if req.AfterID != nil {
|
||||
cursor, err := c.messagesRepo.GetByIDForChat(ctx, req.ChatID, *req.AfterID)
|
||||
if err != nil {
|
||||
return nil, cursorError(err)
|
||||
}
|
||||
query.After = &dto.PagePosition{CreatedAt: cursor.CreatedAt, ID: cursor.ID}
|
||||
}
|
||||
|
||||
items, err := c.messagesRepo.ListForChat(ctx, req.ChatID, query)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return makePage(items, limit, func(message dto.Message) uuid.UUID { return message.ID }), nil
|
||||
}
|
||||
|
||||
func pageLimit(limit *int) (int, error) {
|
||||
size := 50
|
||||
if limit != nil {
|
||||
size = *limit
|
||||
}
|
||||
if size < 1 || size > 100 {
|
||||
return 0, apperr.New(apperr.CodeBadRequest, "invalid limit")
|
||||
}
|
||||
return size, nil
|
||||
}
|
||||
|
||||
func cursorError(err error) error {
|
||||
if apperr.CodeFromError(err) == apperr.CodeNotFound {
|
||||
return apperr.New(apperr.CodeBadRequest, "invalid cursor")
|
||||
}
|
||||
return err
|
||||
}
|
||||
|
||||
func makePage[T any](items []T, limit int, id func(T) uuid.UUID) *dto.Page[T] {
|
||||
if items == nil {
|
||||
items = make([]T, 0)
|
||||
}
|
||||
page := dto.Page[T]{Items: items}
|
||||
if len(items) > limit {
|
||||
page.Items = items[:limit]
|
||||
cursor := id(page.Items[limit-1])
|
||||
page.NextCursorID = &cursor
|
||||
}
|
||||
return &page
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
package user
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"github.com/google/uuid"
|
||||
|
||||
"gitea.privcloud.tech/mtusi2026/internal/dto"
|
||||
)
|
||||
|
||||
type API interface {
|
||||
Create(ctx context.Context, req dto.CreateUser) (*dto.User, error)
|
||||
GetByID(ctx context.Context, id uuid.UUID) (*dto.User, error)
|
||||
GetByUsername(ctx context.Context, username string) (*dto.User, error)
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
package user
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"github.com/google/uuid"
|
||||
|
||||
"gitea.privcloud.tech/mtusi2026/internal/dto"
|
||||
)
|
||||
|
||||
type userRepo interface {
|
||||
Create(ctx context.Context, req dto.CreateStoredUser) error
|
||||
GetByID(ctx context.Context, id uuid.UUID) (*dto.User, error)
|
||||
GetByUsername(ctx context.Context, username string) (*dto.User, error)
|
||||
}
|
||||
@@ -0,0 +1,67 @@
|
||||
package user
|
||||
|
||||
import (
|
||||
"context"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
|
||||
"gitea.privcloud.tech/mtusi2026/internal/dto"
|
||||
"gitea.privcloud.tech/mtusi2026/internal/pkg/apperr"
|
||||
"gitea.privcloud.tech/mtusi2026/internal/pkg/encrypting"
|
||||
)
|
||||
|
||||
var (
|
||||
_ API = (*User)(nil)
|
||||
)
|
||||
|
||||
type User struct {
|
||||
encryptor encrypting.Encryptor
|
||||
usersRepo userRepo
|
||||
}
|
||||
|
||||
func New(encryptor encrypting.Encryptor, usersRepo userRepo) *User {
|
||||
return &User{encryptor: encryptor, usersRepo: usersRepo}
|
||||
}
|
||||
|
||||
func (u *User) Create(ctx context.Context, req dto.CreateUser) (*dto.User, error) {
|
||||
hash, err := u.encryptor.EncryptSecretUsingArgon2id(ctx, req.Password)
|
||||
if err != nil {
|
||||
return nil, apperr.Wrap(err, apperr.CodeInternal, "failed to hash password")
|
||||
}
|
||||
|
||||
user := dto.User{
|
||||
ID: uuid.New(),
|
||||
Username: req.Username,
|
||||
DisplayName: req.DisplayName,
|
||||
CreatedAt: time.Now().Truncate(time.Microsecond),
|
||||
}
|
||||
if err = u.usersRepo.Create(ctx, dto.CreateStoredUser{
|
||||
ID: user.ID,
|
||||
Username: user.Username,
|
||||
DisplayName: user.DisplayName,
|
||||
PasswordHash: hash,
|
||||
CreatedAt: user.CreatedAt,
|
||||
UpdatedAt: user.CreatedAt,
|
||||
}); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return &user, nil
|
||||
}
|
||||
|
||||
func (u *User) GetByID(ctx context.Context, id uuid.UUID) (*dto.User, error) {
|
||||
user, err := u.usersRepo.GetByID(ctx, id)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return user, nil
|
||||
}
|
||||
|
||||
func (u *User) GetByUsername(ctx context.Context, username string) (*dto.User, error) {
|
||||
user, err := u.usersRepo.GetByUsername(ctx, username)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return user, nil
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
CREATE TABLE IF NOT EXISTS users
|
||||
(
|
||||
id UUID PRIMARY KEY,
|
||||
name VARCHAR(100) NOT NULL,
|
||||
username VARCHAR(32) NOT NULL,
|
||||
password_hash TEXT NOT NULL,
|
||||
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
|
||||
updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
|
||||
|
||||
CONSTRAINT users_username_unique UNIQUE (username),
|
||||
CONSTRAINT users_username_format CHECK (username ~ '^[a-z0-9_]{3,32}$'),
|
||||
CONSTRAINT users_name_not_blank CHECK (name !~ '^[[:space:]]*$'),
|
||||
CONSTRAINT users_password_hash_not_empty CHECK (password_hash <> '')
|
||||
);
|
||||
|
||||
---- create above / drop below ----
|
||||
|
||||
DROP TABLE IF EXISTS users;
|
||||
@@ -0,0 +1,19 @@
|
||||
CREATE TABLE IF NOT EXISTS refresh_tokens
|
||||
(
|
||||
id UUID PRIMARY KEY,
|
||||
user_id UUID NOT NULL REFERENCES users (id),
|
||||
token_hash TEXT NOT NULL,
|
||||
user_agent TEXT,
|
||||
ip_address INET,
|
||||
role VARCHAR(16) NOT NULL,
|
||||
expires_at TIMESTAMPTZ NOT NULL,
|
||||
revoked_at TIMESTAMPTZ,
|
||||
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
|
||||
);
|
||||
|
||||
CREATE INDEX IF NOT EXISTS idx_refresh_user_id ON refresh_tokens (user_id);
|
||||
CREATE INDEX IF NOT EXISTS idx_refresh_expires ON refresh_tokens (expires_at);
|
||||
|
||||
---- create above / drop below ----
|
||||
|
||||
DROP TABLE IF EXISTS refresh_tokens;
|
||||
@@ -0,0 +1,14 @@
|
||||
CREATE TABLE IF NOT EXISTS chats
|
||||
(
|
||||
id UUID PRIMARY KEY,
|
||||
title VARCHAR(100) NOT NULL,
|
||||
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
|
||||
|
||||
CONSTRAINT chats_title_not_blank CHECK (title !~ '^[[:space:]]*$')
|
||||
);
|
||||
|
||||
CREATE INDEX IF NOT EXISTS idx_chats_created_at_id ON chats (created_at, id);
|
||||
|
||||
---- create above / drop below ----
|
||||
|
||||
DROP TABLE IF EXISTS chats;
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user