ЛР 2 - БВТ2301 - Хакимов Дмитрий - на 4. #14

Closed
DmitryKhakimov wants to merge 2 commits from DmitryKhakimov/mtusi2026lab2:master into master
88 changed files with 4566 additions and 32 deletions
+9
View File
@@ -1,5 +1,6 @@
.git
.github
.gitignore
.env
.env.*
!.env.example
@@ -17,4 +18,12 @@ backups
__pycache__
node_modules
evidence
examples
scripts
tests
*.md
Dockerfile*
Makefile
requirements-dev.txt
lab.json
.DS_Store
+57
View File
@@ -0,0 +1,57 @@
FROM golang:1.26.4-alpine3.23@sha256:18b460dd17542c2ba43299a633cf6ebfc1115101509531471d7cfce1019af083 AS goose-builder
RUN GOBIN=/out CGO_ENABLED=0 go install \
-tags='no_clickhouse no_libsql no_mssql no_mysql no_sqlite3 no_vertica no_ydb no_spanner' \
github.com/pressly/goose/v3/cmd/goose@v3.27.1
FROM alpine:3.23@sha256:075c2c1a4068c1e251228ca2b0ea8b163f835ca5d66e758b93c7fc89b1995616 AS migrations
COPY --from=goose-builder /out/goose /usr/local/bin/goose
COPY migrations /migrations
COPY infra/migrate.sh /usr/local/bin/migrate
USER 10001:10001
ENTRYPOINT ["/usr/local/bin/migrate"]
CMD ["up"]
FROM golang:1.26.4-alpine3.23@sha256:18b460dd17542c2ba43299a633cf6ebfc1115101509531471d7cfce1019af083 AS builder
WORKDIR /src
RUN apk add --no-cache gcc musl-dev
COPY go.mod go.sum ./
RUN go mod download
COPY cmd ./cmd
COPY contracts ./contracts
COPY dto ./dto
COPY internal ./internal
COPY migrations ./migrations
RUN CGO_ENABLED=0 GOOS=linux go build \
-trimpath \
-ldflags="-s -w" \
-o /out/messenger ./cmd
FROM builder AS tests
COPY --from=goose-builder /out/goose /usr/local/bin/goose
ENV GOOSE_MIGRATION_DIR=/src/migrations
CMD ["go", "test", "-p=1", "-race", "-count=1", "-v", "./..."]
FROM alpine:3.23@sha256:075c2c1a4068c1e251228ca2b0ea8b163f835ca5d66e758b93c7fc89b1995616
RUN addgroup -S messenger \
&& adduser -S -D -H -u 10001 -G messenger messenger
COPY --from=builder --chown=messenger:messenger /out/messenger /usr/local/bin/messenger
ENV PORT=8080
EXPOSE 8080
USER messenger:messenger
HEALTHCHECK --interval=10s --timeout=3s --start-period=3s --retries=3 \
CMD wget -q -O /dev/null "http://127.0.0.1:${PORT}/health/ready" || exit 1
STOPSIGNAL SIGTERM
ENTRYPOINT ["/usr/local/bin/messenger"]
+48 -5
View File
@@ -1,13 +1,18 @@
PYTHON ?= python3
BASE_URL ?= http://localhost:8080
PYTHON ?= $(if $(wildcard .venv/bin/python),.venv/bin/python,python3)
GO ?= go
PORT ?= 8080
BASE_URL ?= http://localhost:$(PORT)
IMAGE ?= mtusi-messenger:lab2
CA_FILE ?=
ACTION_SCRIPT ?=
ACTION_SCRIPT ?= scripts/restart.sh
TLS_ARGS = $(if $(CA_FILE),--ca-file "$(CA_FILE)",)
.PHONY: help check validate test load test-persistence
.PHONY: help run docker-build docker-run check validate test test-own test-all load test-persistence bootstrap up down migrate test-integration test-grade4 measure-load migrate-status migrate-down
export PORT BASE_URL
help:
@echo "check: offline structure; validate: full OpenAPI (requirements-dev.txt); test: running API; load: synthetic writes"
@echo "up: start Compose stack; down: stop with volumes retained; test-integration: PostgreSQL race/rollback/EXPLAIN; test-grade4: auth/expiry/outages; check: offline structure; validate: full OpenAPI (requirements-dev.txt); test: running API; load: synthetic writes"
check:
$(PYTHON) scripts/check_contract.py
@@ -18,9 +23,47 @@ validate:
test:
$(PYTHON) tests/smoke.py --base-url "$(BASE_URL)" $(TLS_ARGS)
test-own:
$(GO) test -race ./...
test-all: check validate test-own
load:
$(PYTHON) tests/load.py --base-url "$(BASE_URL)" $(TLS_ARGS)
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)
bootstrap:
./scripts/bootstrap.sh
up: bootstrap
./scripts/compose.sh up -d --build --wait
down:
./scripts/compose.sh down
migrate: bootstrap
./scripts/compose.sh run --build --rm migrations up
migrate-status:
./scripts/compose.sh run --rm migrations status
migrate-down:
./scripts/compose.sh run --rm migrations down
run:
PORT="$(PORT)" $(GO) run ./cmd
docker-build:
docker build -t "$(IMAGE)" .
test-integration:
./scripts/compose.sh run --build --rm tests
test-grade4:
$(PYTHON) tests/own/grade4.py
measure-load:
$(PYTHON) scripts/measure_load.py --base-url "$(BASE_URL)"
+14 -1
View File
@@ -2,7 +2,20 @@
Перенести состояние в постоянное хранилище и связать запросы с аутентифицированным пользователем. Подтверждённые сообщения и действующие сессии переживают перезапуск.
Это **skeleton**, а не готовый сервер. Здесь есть задание, контракт и публичные проверки. Реализацию приложения, Dockerfile и требуемую инфраструктуру пишет студент. Язык и framework свободные; UI не обязателен.
Реализован стенд на Go/Echo, PostgreSQL и Redis для уровня **4**. Архитектура и
проверенные результаты — в [REPORT.md](REPORT.md), настройки — в [infra/README.md](infra/README.md).
```sh
make up # API на http://localhost:8080, Swagger на /swagger/
make test
make test-integration
make test-persistence ACTION_SCRIPT=scripts/restart.sh
make test-grade4
make down # данные сохраняются
```
По умолчанию используется порт 8080. Ниже сохранены
исходные требования лабораторной и рубрика оценивания.
[Карта курса](COURSE.md) · [Процесс fork/PR](CONTRIBUTING.md) · [OpenAPI](contracts/openapi.json) · [Семантика API](contracts/README.md) · [Проверки](tests/README.md) · [Отчёт](REPORT.md) · [Примеры JSON](contracts/examples.json) · [Памятка преподавателю](MAINTAINERS.md)
+171 -19
View File
@@ -1,37 +1,189 @@
# Отчёт — лабораторная 2
- Автор, группа: TODO
- Целевая оценка; выбранный трек 5, если нужен: TODO
- Commit/PR: TODO после публикации
- Использованные источники, библиотеки и помощь ИИ: TODO
- Автор, группа: не указаны пользователем.
- Целевая оценка: **4**, трек 5 не заявлен.
- Commit/PR: изменения в рабочем дереве; публикация не выполнялась.
- Основа: собственная реализация mtusi2026lab1-fork (Echo, DTO, use case, repository,
cursor, Swagger, HTTP-тесты).
(интерфейс репозитория в use case и внедрение зависимостей),
`everylounge-proxy/internal/pkg/store/postgres/auth_tokens.go` и `internal/config/postgres.go`
(отдельный Storage, параметризованные запросы, ограниченный пул и таймауты).
Корпоративные библиотеки и прикладной код этих проектов не перенесены.
- Библиотеки: pgx v5.7.6, go-redis v9.12.1, Argon2id из golang.org/x/crypto v0.38.0;
остальные версии закреплены в go.mod/go.sum. При реализации и проверках использован Codex.
## Запуск из чистого clone
TODO: версии runtime/образов, prerequisites, команды создания локальных secrets/.env, build, миграций, запуска, ожидания готовности, тестов и остановки. Указать необходимые действия оператора. Не вставлять секреты. Отдельно указать безопасную остановку и команду намеренного удаления учебных данных.
Нужны Docker Engine с Compose v2+ либо standalone Compose, make, openssl, Python 3.9+.
Go на хосте нужен только для `make test-own`/`make run`; интеграционные тесты работают
в контейнере. Go **1.26.4**, runtime Alpine **3.23**, PostgreSQL **17.6-alpine3.22**,
Redis **7.4.5-alpine3.21**. Go/Alpine образы закреплены digest в Dockerfile.
```sh
make up PORT=8080
make test PORT=8080
make migrate PORT=8080
make test-integration PORT=8080
make test-persistence PORT=8080 ACTION_SCRIPT=scripts/restart.sh
make test-grade4 PORT=8080
make down PORT=8080
```
Порт 8080 используется по умолчанию; параметр PORT можно не передавать. API: http://localhost:8080; Swagger: http://localhost:8080/swagger/.
`up --wait` ждёт healthcheck всех трёх сервисов. Bootstrap генерирует локальные
секреты без вывода значений; каталог secrets и volumes исключены из Git и build context.
Повторный bootstrap сохраняет существующие секреты. Настройки и права файлов —
[infra/README.md](infra/README.md). Настройки передаются через Compose и переменные
процесса; локальные env-файлы не требуются. `scripts/compose.sh` явно отключает их
автоматическое чтение. Для запуска API вне Compose настройте адреса БД/Redis и
POSTGRES_PASSWORD_FILE, CURSOR_KEY_FILE, примените `goose up`, затем `make run`.
`make down` сохраняет volumes. **Намеренное удаление всех учебных данных**:
`./scripts/compose.sh down --volumes` — эта команда при проверке не выполнялась.
## Архитектура и решения
TODO: схема процессов/хранилищ, источник истины, транзакционные границы, ограничения. Что перенесено из lab1, что изменено в этой работе. Соответствие переменных из .env.example реальной конфигурации.
```mermaid
flowchart LR
Client[HTTP client] --> Handler[Echo handlers / DTO]
Handler --> UseCase[Chat use case]
UseCase --> PG[PostgreSQL: users / chats / members / messages]
UseCase --> Redis[Redis: sessions + TTL + AOF]
```
Интерфейсы хранения объявлены в use case. PostgreSQL-адаптер —
`internal/pkg/repository/postgres`, Redis-адаптер — `internal/pkg/session`.
Memory-репозиторий lab1 оставлен для быстрых Go-тестов; запускаемый сервер использует
только PostgreSQL и Redis. DTO отделены от доменных моделей, SQL/Redis не входят в HTTP-обработчики.
Схема, индексы и границы транзакций описаны до реализации запросов в
[infra/schema.md](infra/schema.md). Миграцию `001_initial.sql` с секциями Up/Down
применяет **goose CLI v3.27.1** в отдельном сервисе Compose. API запускается после
его успешного завершения и сам миграции не выполняет. DDL и запись в
`goose_db_version` коммитятся атомарно. Повторный `goose up` не дублирует таблицы
или данные. Переход с прежнего `schema_migrations` сохраняет существующие данные;
команды `make migrate`, `make migrate-status`, `make migrate-down` описаны в
[infra/README.md](infra/README.md). Down начальной миграции удаляет таблицы и данные. Создание чата и всех участников — одна транзакция;
FK проверяет существование пользователя. UNIQUE(username) разрешает гонку регистрации.
Проверки перехода на goose сохранены отдельно: [goose.txt](evidence/goose.txt)
подтверждает сохранение прежнего токена и сообщения на работающем стенде;
[goose-integration.txt](evidence/goose-integration.txt) — применение с нуля,
повторный up, сохранение 10 000 сообщений при смене журнала и down/up в отдельной
тестовой схеме. В рабочей БД выполнялся только up; down проверялся на тестовой схеме.
SQL использует параметры `$1...`; pool ограничен 10 соединениями, SQL/соединение/
Redis/ожидание пула имеют таймаут 2 секунды. Чтение истории — keyset по
`(created_at,id)` с индексом `(chat_id,created_at,id)` и LIMIT+1; OFFSET не используется.
Ключ HMAC cursor создаётся отдельно и сохраняется при рестарте. JSON timestamps
имеют ровно 6 знаков дробной части для совместимости с Python 3.9, без потери
точности PostgreSQL. При конкурентных вставках это не snapshot: поздний COMMIT
с ключом до cursor может быть пропущен; неизменная история обходится без повторов.
Регистрация принимает пароль 12–128 Unicode code points. Argon2id: 19 MiB, 2 прохода,
parallelism=1, соль 16 случайных байт, результат 32 байта; сравнение constant-time.
Семафор ограничивает одновременно выполняемые KDF четырьмя. UTF-8 не обрезается.
Для отсутствующего username выполняется фиктивная KDF-проверка, ошибка входа одинакова.
Basic принимается только при создании сессии. Токен — 32 случайных байта в base64url;
в Redis хранится SHA-256 токена, user_id и абсолютное expires_at. Пароль и hash
никогда не попадают в User. Bearer проверяется по Redis, затем пользователь читается
из PostgreSQL; X-User-Id игнорируется. Сессии не продлеваются чтением или рестартом.
Logout удаляет ключ, повтор возвращает 401. Redis SET PXAT задаёт абсолютный срок,
дополнительно expires_at проверяется приложением. По умолчанию TTL=3600 секунд.
Redis — единственное хранилище сессий; AOF с appendfsync=always и именованный volume
сохраняют сессии при проверенном рестарте. maxmemory=64 MiB, noeviction: Redis не
выбрасывает действующие сессии при нехватке памяти, новая запись получает 503.
Кэша истории нет, следующий запрос после успешной записи читает подтверждённые данные
PostgreSQL. Обе зависимости критичны для readiness. При отказе — 503 unavailable
без SQL/credentials, при отсутствии Bearer — 401, liveness остаётся 200.
## Доказательства критериев
| Критерий README | Команда/сценарий | Наблюдаемый результат | Файл доказательства |
| --- | --- | --- | --- |
| Публичный smoke | make test | TODO | TODO |
| Остальные пункты уровня 3 | TODO | TODO | TODO |
| Все пункты уровня 4, если заявлен | TODO | TODO | TODO |
| Выбранный трек 5, если заявлен | TODO | TODO | TODO |
Публичные контракты и `tests/*.py` не изменены. Собственные HTTP-проверки находятся
в `tests/own/`, Go integration test создаёт и затем удаляет только свою отдельную схему.
TODO: добавить отдельную строку для каждого заявленного критерия. PASS без команды и наблюдения не является доказательством. Проверка инфраструктурного hook требует подтверждения, какие реальные процессы/хранилища перезапущены.
| Критерий | Команда / сценарий | Результат | Доказательство |
| --- | --- | --- | --- |
| Минимум API, новый контракт lab2 | `make test PORT=8080` | PASS | [smoke.txt](evidence/smoke.txt) |
| PostgreSQL, PK/FK/UNIQUE, атомарность чата | `make test-integration PORT=8080` | PASS: PK/FK, UNIQUE и rollback подтверждены | [integration.txt](evidence/integration.txt) |
| Повтор миграций | `make migrate`, integration test | Одна версия после двух применений | [integration.txt](evidence/integration.txt) |
| Basic/Bearer, KDF, неверный пароль, logout | `make test-grade4 PORT=8080` | PASS, также Unicode 128 code points с двоеточием | [grade4.txt](evidence/grade4.txt) |
| Сохранность сообщений и сессий | `make test-persistence PORT=8080 ACTION_SCRIPT=scripts/restart.sh` | PASS: прежний токен читает то же сообщение после рестарта всех трёх сервисов | [persistence.txt](evidence/persistence.txt) |
| Redis TTL и persistence | grade4 + persistence | Истечение и сохранение действующей сессии | [grade4.txt](evidence/grade4.txt) |
| Гонка регистрации | integration + grade4 | 12 SQL / 8 HTTP запросов; ровно один успех | [integration.txt](evidence/integration.txt), [grade4.txt](evidence/grade4.txt) |
| Rollback составной операции | integration | После ошибки второго участника: 0 чатов, 0 участников | [integration.txt](evidence/integration.txt) |
| Индекс, 10 000 сообщений, EXPLAIN ANALYZE BUFFERS | integration | Index Scan, 51 строка, 5 shared buffers, без Sort/Seq Scan | [integration.txt](evidence/integration.txt) |
| Недоступность Redis и PostgreSQL | grade4 останавливает каждый сервис отдельно | live=200, ready/protected=503, anonymous=401, после старта прежняя сессия работает | [grade4.txt](evidence/grade4.txt) |
| Короткий TTL | API пересоздаётся с TTL=2, затем TTL=3600 | 401 после истечения и рестарта Redis | [grade4.txt](evidence/grade4.txt) |
## Эксперименты и отказы
TODO: гипотеза, hardware/лимиты, версии, объём данных, профиль нагрузки, concurrency/arrival rate, длительность/прогрев, повторы, успешные RPS, ошибки, p50/p95/p99, CPU/RAM. Сохранить raw summary без tokens и объяснить ограничения измерения.
Стенд проверки: Docker/Colima Linux aarch64, **2 vCPU, 2 053 652 480 байт RAM** VM.
Engine 29.5.2, Compose 5.1.4. Лимиты: API 1 CPU / 256 MiB, PostgreSQL 1 CPU / 512 MiB,
Redis 0.5 CPU / 128 MiB; контейнер тестов 1 CPU / 1 GiB, тестовые пакеты компилируются
последовательно (`-p=1`). Первый race-build Redis в тестовом лимите 512 MiB был убит
по памяти; тестовый лимит увеличен, лимиты самого стенда не изменялись.
| Воздействие | Что ожидаем | Что наблюдали | Время восстановления / потеря данных |
| --- | --- | --- | --- |
| TODO | TODO | TODO | TODO |
Проверки выполнены **6 октября 2026 года**. Полный вывод Go race tests и EXPLAIN:
[integration.txt](evidence/integration.txt). На 10 000 сообщениях, страница
около 9000-го сообщения: `Limit → Index Scan using messages_history_idx`,
51 возвращённая строка, `Buffers: shared hit=5`, Planning Time **0.029 ms**,
Execution Time **0.035 ms**. Сортировка явно использует `m.created_at, m.id`,
а не текстовый alias результата. Seq Scan, OFFSET и дополнительного Sort нет.
Полный обход с шагом 97 получил все 10 000 уникальных ID, включая группы
с одинаковым временем.
## Ограничения и следующие шаги
`make measure-load PORT=8080` выполняет 3 секунды прогрева, затем 30 секунд
closed-loop POST сообщений с конкуренцией 4. Один измерительный прогон:
**25 398 успешных запросов, 0 ошибок, 846.152 успешных RPS**;
p50 **4.419 ms**, p95 **6.588 ms**, p99 **10.795 ms**. До прогона: 25 пользователей,
6 чатов, 2471 сообщение; после: 28 пользователей, 7 чатов, 27 869 сообщений.
Результат: [load.json](evidence/load.json); 10 выборок Docker stats и размеры данных:
[resources.json](evidence/resources.json).
TODO: какие отказы выдерживаются и какие нет; что не реализовано; где учебное упрощение; какое улучшение подтверждено, а какое пока гипотеза.
Максимумы среди полученных выборок (не гарантированные мгновенные пики):
| Сервис | CPU | RAM |
| --- | --- | --- |
| API | 32.14% | 10.65 MiB |
| PostgreSQL | 33.06% | 39.58 MiB |
| Redis | 3.53% | 3.387 MiB |
Тестовый контейнер во время измерения не работал. Клиент — Python на хосте,
сеть через Colima; процентили относятся к успешным ответам, профиль closed-loop
имеет coordinated omission. Сравнение альтернативных архитектур не проводилось.
| Воздействие | Наблюдение | Восстановление / данные |
| --- | --- | --- |
| Остановка API + PostgreSQL + Redis | Публичный persistence PASS; StartedAt всех сервисов изменился | Тот же токен и то же подтверждённое сообщение; volumes сохранены |
| Остановка Redis | live=200, ready=503, Bearer=503, anonymous=401 | После запуска прежний токен работает, отозванный остаётся 401 |
| Остановка PostgreSQL | live=200, ready=503, Bearer=503, anonymous=401 | После запуска прежний токен работает |
| SESSION_TTL_SECONDS=2 | Сначала 200, после 2.2 s — 401 | Рестарт Redis не возрождает сессию; затем восстановлен TTL=3600 |
| Рестарт только API | Старый подписанный cursor и Bearer работают | Ключ HMAC и сессии не изменились |
В полном рестарте API снова стартовал через **2.634 s** после старта Redis,
готовность и чтение проверены публичным сценарием; это не замер полного RTO.
Точные StartedAt до/после: [persistence.txt](evidence/persistence.txt).
При отдельных отказах собственный тест проверяет ответ readiness быстрее 4 секунд
с таймаутом клиента 5 секунд. Потерь подтверждённых данных в этих сценариях не обнаружено.
Структурная проверка выполнена на чистом снимке исходников без локальных ignored-файлов:
[check.txt](evidence/check.txt). Полная проверка OpenAPI и JSON Schema:
[validation.txt](evidence/validation.txt).
## Ограничения
Один Docker-host и по одному PostgreSQL/Redis не обеспечивают HA. Проверяется
рестарт процессов с сохранёнными volumes, а не потеря диска/host или восстановление
из backup. fsync/AOF зависят от гарантий файловой системы и оборудования. Удаление
Redis volume уничтожит сессии; пользователи и сообщения останутся в PostgreSQL.
Истёкшие сессии удаляются Redis автоматически; пароль не меняется в обязательном API.
HTTP и Redis без TLS/ACL допустимы только в этом локальном учебном стенде:
БД/Redis не публикуют порты, HTTP доступен на loopback, данные синтетические.
PostgreSQL использует одну учебную роль для миграций и API. Разделение ролей, TLS,
rate limiting и распределённое ограничение KDF — отдельные улучшения.
Нагрузка closed-loop показывает поведение этой конфигурации, не предел пропускной
способности и не SLA. Треки оценки 5, резервное копирование и репликация не заявлены.
+97
View File
@@ -0,0 +1,97 @@
package main
import (
"context"
"errors"
"fmt"
"log"
"net/http"
"os"
"os/signal"
"syscall"
"time"
"github.com/jackc/pgx/v5/pgxpool"
"github.com/redis/go-redis/v9"
"gitflic.ru/akselbant/mtusi2026lab1-fork/internal/app/chat"
"gitflic.ru/akselbant/mtusi2026lab1-fork/internal/config"
"gitflic.ru/akselbant/mtusi2026lab1-fork/internal/pkg/repository/postgres"
"gitflic.ru/akselbant/mtusi2026lab1-fork/internal/pkg/session"
chatusecase "gitflic.ru/akselbant/mtusi2026lab1-fork/internal/usecase/chat"
)
const shutdownTimeout = 8 * time.Second
func main() {
cfg, err := config.Load()
if err != nil {
log.Fatal(err)
}
poolConfig, err := pgxpool.ParseConfig("sslmode=disable")
if err != nil {
log.Fatal("invalid PostgreSQL config")
}
poolConfig.ConnConfig.Host = cfg.PostgresHost
poolConfig.ConnConfig.Port = cfg.PostgresPort
poolConfig.ConnConfig.User = cfg.PostgresUser
poolConfig.ConnConfig.Database = cfg.PostgresDatabase
poolConfig.ConnConfig.Password = cfg.PostgresPassword
poolConfig.ConnConfig.ConnectTimeout = cfg.QueryTimeout
poolConfig.ConnConfig.RuntimeParams["timezone"] = "UTC"
poolConfig.ConnConfig.RuntimeParams["statement_timeout"] = fmt.Sprint(cfg.QueryTimeout.Milliseconds())
poolConfig.MaxConns = cfg.PostgresMaxConns
poolConfig.MinConns = 1
poolConfig.MaxConnLifetime = time.Hour
poolConfig.MaxConnIdleTime = 5 * time.Minute
pool, err := pgxpool.NewWithConfig(context.Background(), poolConfig)
if err != nil {
log.Fatal("cannot create PostgreSQL pool")
}
defer pool.Close()
redisClient := redis.NewClient(&redis.Options{
Addr: cfg.RedisAddr, PoolSize: 10, MaxActiveConns: 10, PoolTimeout: cfg.QueryTimeout,
DialTimeout: cfg.QueryTimeout, ReadTimeout: cfg.QueryTimeout, WriteTimeout: cfg.QueryTimeout,
MaxRetries: -1, ContextTimeoutEnabled: true,
})
defer redisClient.Close()
repo := postgres.New(pool, cfg.QueryTimeout)
sessions := session.NewRedis(redisClient, cfg.QueryTimeout)
useCase := chatusecase.New(repo, sessions, cfg.SessionTTL)
handler := chat.NewChat(useCase, cfg.CursorKey)
port := cfg.Port
e := handler.Router()
e.Server.ReadHeaderTimeout = 5 * time.Second
e.Server.ReadTimeout = 10 * time.Second
e.Server.WriteTimeout = 15 * time.Second
e.Server.IdleTimeout = 60 * time.Second
serverErrors := make(chan error, 1)
go func() {
log.Printf("HTTP server is listening on :%s", port)
serverErrors <- e.Start(":" + port)
}()
stop := make(chan os.Signal, 1)
signal.Notify(stop, syscall.SIGINT, syscall.SIGTERM)
select {
case sig := <-stop:
log.Printf("received %s, shutting down", sig)
case err := <-serverErrors:
if !errors.Is(err, http.ErrServerClosed) {
log.Fatalf("HTTP server failed: %v", err)
}
return
}
ctx, cancel := context.WithTimeout(context.Background(), shutdownTimeout)
defer cancel()
if err := e.Shutdown(ctx); err != nil {
log.Printf("graceful shutdown failed: %v", err)
if closeErr := e.Close(); closeErr != nil {
log.Printf("forced shutdown failed: %v", closeErr)
}
return
}
log.Printf("shutdown complete")
}
+101
View File
@@ -0,0 +1,101 @@
name: mtusi2026lab2
services:
postgres:
image: postgres:17.6-alpine3.22
environment:
POSTGRES_USER: messenger
POSTGRES_DB: messenger
POSTGRES_PASSWORD_FILE: /run/secrets/postgres_password
secrets:
- postgres_password
volumes:
- postgres_data:/var/lib/postgresql/data
healthcheck:
test: [CMD-SHELL, 'pg_isready -U messenger -d messenger']
interval: 2s
timeout: 2s
retries: 30
cpus: 1.0
mem_limit: 512m
redis:
image: redis:7.4.5-alpine3.21
command: [redis-server, /usr/local/etc/redis/redis.conf]
volumes:
- redis_data:/data
- ./infra/redis.conf:/usr/local/etc/redis/redis.conf:ro
healthcheck:
test: [CMD, redis-cli, ping]
interval: 2s
timeout: 2s
retries: 30
cpus: 0.5
mem_limit: 128m
migrations:
image: mtusi-migrations:lab2
build:
context: .
target: migrations
environment:
GOOSE_DRIVER: postgres
GOOSE_DBSTRING: host=postgres user=messenger dbname=messenger sslmode=disable connect_timeout=5
POSTGRES_PASSWORD_FILE: /run/secrets/postgres_password
secrets:
- postgres_password
depends_on:
postgres:
condition: service_healthy
cpus: 0.5
mem_limit: 128m
api:
build: .
image: mtusi-messenger:lab2
environment: &api_environment
POSTGRES_HOST: postgres
POSTGRES_USER: messenger
POSTGRES_DB: messenger
POSTGRES_PASSWORD_FILE: /run/secrets/postgres_password
POSTGRES_MAX_CONNS: '10'
REDIS_ADDR: redis:6379
CURSOR_KEY_FILE: /run/secrets/cursor_key
SESSION_TTL_SECONDS: ${SESSION_TTL_SECONDS:-3600}
QUERY_TIMEOUT_MS: '2000'
secrets: &api_secrets
- postgres_password
- cursor_key
ports:
- '127.0.0.1:${PORT:-8080}:8080'
depends_on:
postgres:
condition: service_healthy
redis:
condition: service_healthy
migrations:
condition: service_completed_successfully
cpus: 1.0
mem_limit: 256m
stop_grace_period: 10s
tests:
image: mtusi-messenger-tests:lab2
profiles: [test]
build:
context: .
target: tests
environment:
<<: *api_environment
INTEGRATION_TESTS: '1'
secrets: *api_secrets
depends_on:
postgres:
condition: service_healthy
redis:
condition: service_healthy
cpus: 1.0
mem_limit: 1g
secrets:
postgres_password:
file: ./secrets/postgres_password
cursor_key:
file: ./secrets/cursor_key
volumes:
postgres_data:
redis_data:
+9
View File
@@ -0,0 +1,9 @@
package contracts
import _ "embed"
// OpenAPI is embedded so Swagger UI works from a compiled binary and does not
// depend on the process working directory.
//
//go:embed openapi.json
var OpenAPI []byte
+13
View File
@@ -0,0 +1,13 @@
package dto
type CreateChatRequest struct {
Title string `json:"title"`
MemberIDs []string `json:"member_ids"`
}
type CreateChatResponse struct {
ID string `json:"id"`
Title string `json:"title"`
MemberIDs []string `json:"member_ids"`
CreatedAt Timestamp `json:"created_at"`
}
+14
View File
@@ -0,0 +1,14 @@
package dto
type CreateMessageRequest struct {
ChatID string `json:"-"`
Text string `json:"text"`
}
type CreateMessageResponse struct {
ID string `json:"id"`
ChatID string `json:"chat_id"`
SenderID string `json:"sender_id"`
Text string `json:"text"`
CreatedAt Timestamp `json:"created_at"`
}
+14
View File
@@ -0,0 +1,14 @@
package dto
type CreateUserRequest struct {
Password string `json:"password"`
Username string `json:"username"`
DisplayName string `json:"display_name"`
}
type CreateUserResponse struct {
ID string `json:"id"`
Username string `json:"username"`
DisplayName string `json:"display_name"`
CreatedAt Timestamp `json:"created_at"`
}
+10
View File
@@ -0,0 +1,10 @@
package dto
type CurrentUserRequest struct{}
type CurrentUserResponse struct {
ID string `json:"id"`
Username string `json:"username"`
DisplayName string `json:"display_name"`
CreatedAt Timestamp `json:"created_at"`
}
+11
View File
@@ -0,0 +1,11 @@
package dto
type ErrorResponse struct {
Error ErrorDetails `json:"error"`
}
type ErrorDetails struct {
Code string `json:"code"`
Message string `json:"message"`
RequestID string `json:"request_id"`
}
+12
View File
@@ -0,0 +1,12 @@
package dto
type GetChatRequest struct {
ChatID string `json:"-"`
}
type GetChatResponse struct {
ID string `json:"id"`
Title string `json:"title"`
MemberIDs []string `json:"member_ids"`
CreatedAt Timestamp `json:"created_at"`
}
+18
View File
@@ -0,0 +1,18 @@
package dto
type ListChatsRequest struct {
Limit int `json:"-"`
Cursor string `json:"-"`
}
type ListChatsResponse struct {
Items []ListChatsItem `json:"items"`
NextCursor *string `json:"next_cursor"`
}
type ListChatsItem struct {
ID string `json:"id"`
Title string `json:"title"`
MemberIDs []string `json:"member_ids"`
CreatedAt Timestamp `json:"created_at"`
}
+20
View File
@@ -0,0 +1,20 @@
package dto
type ListMessagesRequest struct {
ChatID string `json:"-"`
Limit int `json:"-"`
Cursor string `json:"-"`
}
type ListMessagesResponse struct {
Items []ListMessagesItem `json:"items"`
NextCursor *string `json:"next_cursor"`
}
type ListMessagesItem struct {
ID string `json:"id"`
ChatID string `json:"chat_id"`
SenderID string `json:"sender_id"`
Text string `json:"text"`
CreatedAt Timestamp `json:"created_at"`
}
+7
View File
@@ -0,0 +1,7 @@
package dto
type LivenessRequest struct{}
type LivenessResponse struct {
Status string `json:"status"`
}
+7
View File
@@ -0,0 +1,7 @@
package dto
type ReadinessRequest struct{}
type ReadinessResponse struct {
Status string `json:"status"`
}
+8
View File
@@ -0,0 +1,8 @@
package dto
type CreateSessionResponse struct {
Token string `json:"token"`
TokenType string `json:"token_type"`
ExpiresAt Timestamp `json:"expires_at"`
User CreateUserResponse `json:"user"`
}
+11
View File
@@ -0,0 +1,11 @@
package dto
import "time"
// Timestamp preserves PostgreSQL microseconds and is readable by Python 3.9 clients.
// time.Time's variable-length fractional part is not supported by those clients.
type Timestamp time.Time
func (t Timestamp) MarshalJSON() ([]byte, error) {
return []byte(`"` + time.Time(t).UTC().Format("2006-01-02T15:04:05.000000Z") + `"`), nil
}
+15
View File
@@ -0,0 +1,15 @@
package dto
import (
"encoding/json"
"testing"
"time"
)
func TestTimestampFixedMicroseconds(t *testing.T) {
timestamp := Timestamp(time.Date(2026, 1, 2, 3, 4, 5, 123400000, time.UTC))
encoded, err := json.Marshal(timestamp)
if err != nil || string(encoded) != `"2026-01-02T03:04:05.123400Z"` {
t.Fatalf("timestamp=%s err=%v", encoded, err)
}
}
+20 -3
View File
@@ -1,5 +1,22 @@
# Доказательства
# Результаты проверки lab2 на оценку 4
Храните небольшие обезличенные результаты: команды и stdout проверок, JSON/CSV агрегатов нагрузки, EXPLAIN, dashboard JSON, текст разбора отказа. Укажите дату, commit, аппаратные лимиты и профиль нагрузки.
Все данные синтетические. Пароли, сессионные токены и содержимое secrets не записываются.
Не добавляйте .env, session tokens, cookies, приватные ключи, credentials, реальные сообщения, raw dumps и signed URLs. Для скриншотов скрывайте секреты. Большие логи/бинарные traces сохраняйте отдельно по правилам преподавателя; одного скриншота без методики недостаточно.
- `check.txt`, `validation.txt` — структура исходников и OpenAPI/JSON Schema.
- `smoke.txt` — публичный API-сценарий.
- `migrations.txt` — повтор применения миграций на работающем стенде.
- `integration.txt` — Go race tests, гонка регистрации, rollback, keyset и EXPLAIN на 10 000 сообщений.
- `persistence.txt` — полный рестарт с прежним токеном; StartedAt всех трёх контейнеров до/после подтверждает область воздействия.
- `grade4.txt` — неверный пароль, Unicode, logout/expiry, HTTP-гонка, реальные отказы PostgreSQL/Redis и восстановление.
- `load.json`, `resources.json`, `environment.txt` — нагрузка, выборки ресурсов, размеры набора и характеристики Docker VM.
Команды, наблюдения и ограничения приведены в [REPORT.md](../REPORT.md).
Переход на goose CLI:
- `goose.txt` — существующая сессия и сообщение сохранены при смене механизма миграций.
- `goose-integration.txt` — свежий прогон race tests, goose up/repeat/legacy/down/up.
- `goose-persistence.txt` — полный рестарт после перевода запуска на сервис migrations.
Адреса и порты в строках команд прежних прогонов приведены к текущей настройке
8080; исходные результаты и измерения сохранены. Smoke повторён на текущем порту.
+3
View File
@@ -0,0 +1,3 @@
Checked a clean source snapshot (ignored local files excluded).
python3 scripts/check_contract.py
PASS: offline skeleton structure, local refs and Python syntax; application NOT tested.
+1
View File
@@ -0,0 +1 @@
architecture=aarch64 CPUs=2 RAM_bytes=2053652480 Engine=29.5.2
+223
View File
@@ -0,0 +1,223 @@
Command: make test-integration PORT=8080
Goose v3.27.1; Go race tests
? gitflic.ru/akselbant/mtusi2026lab1-fork/cmd [no test files]
? gitflic.ru/akselbant/mtusi2026lab1-fork/contracts [no test files]
=== RUN TestTimestampFixedMicroseconds
--- PASS: TestTimestampFixedMicroseconds (0.00s)
PASS
ok gitflic.ru/akselbant/mtusi2026lab1-fork/dto 1.015s
=== RUN TestRejectsMalformedJSON
2026/10/06 19:21:07 request_id=0441a033-226b-4263-a247-9380411a5214 method=POST path=/api/v1/users status=400 response_bytes=140 latency=128.901µs
--- PASS: TestRejectsMalformedJSON (0.00s)
=== RUN TestHidesForeignChat
2026/10/06 19:21:08 request_id=a3224f89-b210-41ba-89d9-9ec909cf8a61 method=POST path=/api/v1/users status=201 response_bytes=141 latency=330.335243ms
2026/10/06 19:21:08 request_id=e3e94884-5408-4fb5-9eff-f80ea954b7d4 method=POST path=/api/v1/auth/sessions status=201 response_bytes=269 latency=298.744996ms
2026/10/06 19:21:08 request_id=bf12dd30-8fc7-40b2-bb8b-8e2cba874bde method=POST path=/api/v1/users status=201 response_bytes=147 latency=282.731024ms
2026/10/06 19:21:08 request_id=6433a955-279e-45ed-a81e-8553ee4c1095 method=POST path=/api/v1/auth/sessions status=201 response_bytes=275 latency=282.634606ms
2026/10/06 19:21:08 request_id=651524c9-39ee-4011-89e0-f95aec822c08 method=POST path=/api/v1/chats status=201 response_bytes=163 latency=150.186µs
2026/10/06 19:21:08 request_id=f9005e92-40d8-4f1f-ba22-3c52b0ee8ea4 method=GET path=/api/v1/chats/:chat_id status=404 response_bytes=126 latency=50.27µs
--- PASS: TestHidesForeignChat (1.20s)
=== RUN TestRejectsEmptyMessage
2026/10/06 19:21:09 request_id=a9fc1932-2fc6-4d11-a545-384a05871499 method=POST path=/api/v1/users status=201 response_bytes=157 latency=277.86131ms
2026/10/06 19:21:09 request_id=998e1cde-edb2-4d22-855b-2b466fc53dcd method=POST path=/api/v1/auth/sessions status=201 response_bytes=285 latency=284.225421ms
2026/10/06 19:21:09 request_id=cb48bfd6-0668-4d88-9025-d61d2d2990f2 method=POST path=/api/v1/chats status=201 response_bytes=163 latency=95.336µs
2026/10/06 19:21:09 request_id=956e8be1-7a1b-4310-bdae-7972cc16fbad method=POST path=/api/v1/chats/:chat_id/messages status=400 response_bytes=172 latency=114.62µs
--- PASS: TestRejectsEmptyMessage (0.57s)
=== RUN TestRejectsDuplicateUsername
2026/10/06 19:21:09 request_id=72777bcd-188c-48cc-a7de-0bc61725248f method=POST path=/api/v1/users status=201 response_bytes=149 latency=311.61798ms
2026/10/06 19:21:10 request_id=5ab95a3a-07b9-40f2-809a-92d7d7483edf method=POST path=/api/v1/auth/sessions status=201 response_bytes=277 latency=279.947026ms
2026/10/06 19:21:10 request_id=e0622122-976a-4bc5-b9a4-345376771661 method=POST path=/api/v1/users status=409 response_bytes=170 latency=281.430809ms
--- PASS: TestRejectsDuplicateUsername (0.88s)
=== RUN TestPaginatesMessagesAcrossMultiplePages
2026/10/06 19:21:10 request_id=9d819d9f-35c6-4a50-808a-7087a4921e62 method=POST path=/api/v1/users status=201 response_bytes=151 latency=279.442201ms
2026/10/06 19:21:10 request_id=c29bdacf-c029-46aa-a02c-f809b8c2e47c method=POST path=/api/v1/auth/sessions status=201 response_bytes=279 latency=276.345812ms
2026/10/06 19:21:10 request_id=3c959364-365e-44a4-bf3b-74d715026fa6 method=POST path=/api/v1/chats status=201 response_bytes=163 latency=91.84µs
2026/10/06 19:21:10 request_id=2bd14676-d7da-440f-ad34-a9979bde21c1 method=POST path=/api/v1/chats/:chat_id/messages status=201 response_bytes=208 latency=105.751µs
2026/10/06 19:21:10 request_id=763351c7-8da6-43ad-b55e-c8bd5162d054 method=POST path=/api/v1/chats/:chat_id/messages status=201 response_bytes=208 latency=65.35µs
2026/10/06 19:21:10 request_id=2927370f-7580-42c2-8f73-acfe4f924fec method=POST path=/api/v1/chats/:chat_id/messages status=201 response_bytes=208 latency=81.011µs
2026/10/06 19:21:10 request_id=d94a3bfc-d62b-4930-8dcf-92d586ee6a98 method=POST path=/api/v1/chats/:chat_id/messages status=201 response_bytes=208 latency=64.892µs
2026/10/06 19:21:10 request_id=13c255b8-91ab-4f97-a48a-40c3b605f449 method=POST path=/api/v1/chats/:chat_id/messages status=201 response_bytes=208 latency=79.469µs
2026/10/06 19:21:10 request_id=b44c9e32-ccb6-49e0-bb39-ac3b57598de1 method=POST path=/api/v1/chats/:chat_id/messages status=201 response_bytes=208 latency=72.764µs
2026/10/06 19:21:10 request_id=2ef87637-534a-40db-88d8-5bf77545d51c method=POST path=/api/v1/chats/:chat_id/messages status=201 response_bytes=208 latency=63.475µs
2026/10/06 19:21:10 request_id=fa13c54b-2f64-41b8-8438-086ec08ccdaa method=GET path=/api/v1/chats/:chat_id/messages status=200 response_bytes=685 latency=235.451µs
2026/10/06 19:21:10 request_id=3a67f145-e4c2-4467-93c7-15e0d030a347 method=GET path=/api/v1/chats/:chat_id/messages status=200 response_bytes=685 latency=159.647µs
2026/10/06 19:21:10 request_id=e9079767-40b1-439c-b4a9-8a6ef7bb2418 method=GET path=/api/v1/chats/:chat_id/messages status=200 response_bytes=685 latency=136.823µs
2026/10/06 19:21:10 request_id=4415807d-e50f-4fff-9f40-62431fb58896 method=GET path=/api/v1/chats/:chat_id/messages status=200 response_bytes=239 latency=154.94µs
--- PASS: TestPaginatesMessagesAcrossMultiplePages (0.57s)
=== RUN TestConcurrentMessagesAreUnique
2026/10/06 19:21:11 request_id=c7f3e148-b835-4e12-a05b-7b14a96afc47 method=POST path=/api/v1/users status=201 response_bytes=153 latency=316.770305ms
2026/10/06 19:21:11 request_id=a3a54cc9-3a3a-48fb-80dd-825c5387cccc method=POST path=/api/v1/auth/sessions status=201 response_bytes=281 latency=276.768392ms
2026/10/06 19:21:11 request_id=a472cedf-ed17-4bb8-9691-539dc74dc7fd method=POST path=/api/v1/users status=201 response_bytes=153 latency=287.071573ms
2026/10/06 19:21:12 request_id=4b55614a-8e73-4829-b3b8-f0adc7dea8ee method=POST path=/api/v1/auth/sessions status=201 response_bytes=281 latency=287.734585ms
2026/10/06 19:21:12 request_id=94245e8d-7b2e-4e15-b8df-e472f60d0cc5 method=POST path=/api/v1/users status=201 response_bytes=153 latency=297.341306ms
2026/10/06 19:21:12 request_id=cc3bdcfe-4cd4-419d-a2a3-8ecd61c2a0a5 method=POST path=/api/v1/auth/sessions status=201 response_bytes=281 latency=310.821696ms
2026/10/06 19:21:13 request_id=9cef771d-6d80-4998-be20-d35bdedad20e method=POST path=/api/v1/users status=201 response_bytes=153 latency=285.441241ms
2026/10/06 19:21:13 request_id=f0cc7457-df88-4afb-885a-f6307c25ad01 method=POST path=/api/v1/auth/sessions status=201 response_bytes=281 latency=282.669521ms
2026/10/06 19:21:13 request_id=881c0abc-72dd-4f9f-a0df-165d91cb0a0c method=POST path=/api/v1/users status=201 response_bytes=153 latency=276.330156ms
2026/10/06 19:21:13 request_id=170c6bbe-f315-49e9-876b-abdf4c1cc01a method=POST path=/api/v1/auth/sessions status=201 response_bytes=281 latency=279.385439ms
2026/10/06 19:21:14 request_id=0aeeb0eb-c4a6-4d50-a850-3cbf7b808827 method=POST path=/api/v1/users status=201 response_bytes=153 latency=317.071453ms
2026/10/06 19:21:14 request_id=0503f41e-c68a-414b-ae08-3830b2a9f0e3 method=POST path=/api/v1/auth/sessions status=201 response_bytes=281 latency=283.199011ms
2026/10/06 19:21:14 request_id=27c6a6b3-fb8d-4e2e-b315-9189fd9fb913 method=POST path=/api/v1/users status=201 response_bytes=153 latency=274.624402ms
2026/10/06 19:21:15 request_id=60d5e268-cffb-4b41-9c2e-2273dbcb41dd method=POST path=/api/v1/auth/sessions status=201 response_bytes=281 latency=276.830342ms
2026/10/06 19:21:15 request_id=182e1fdc-c1ea-4324-a48a-b9aa35d7196b method=POST path=/api/v1/users status=201 response_bytes=153 latency=280.103689ms
2026/10/06 19:21:15 request_id=4eee9c0d-d346-4705-b2a7-98e01dd508c9 method=POST path=/api/v1/auth/sessions status=201 response_bytes=281 latency=309.351113ms
2026/10/06 19:21:15 request_id=18bb0cb3-cdce-41b2-9c19-e4c787347fe4 method=POST path=/api/v1/users status=201 response_bytes=153 latency=281.188701ms
2026/10/06 19:21:16 request_id=06a1834e-2d22-47c0-bda8-fec522218a6e method=POST path=/api/v1/auth/sessions status=201 response_bytes=281 latency=279.685237ms
2026/10/06 19:21:16 request_id=311cd27d-9c40-4fff-934e-31f8704f0850 method=POST path=/api/v1/users status=201 response_bytes=153 latency=285.577178ms
2026/10/06 19:21:16 request_id=0f05c096-ae0c-4d45-b2d2-798a8a8148bb method=POST path=/api/v1/auth/sessions status=201 response_bytes=281 latency=280.435076ms
2026/10/06 19:21:16 request_id=b06753b1-0bef-4315-852e-09196ba32d8b method=POST path=/api/v1/chats status=201 response_bytes=514 latency=170.244µs
2026/10/06 19:21:16 request_id=cab4660e-7247-4070-a104-155374f4a4ac method=POST path=/api/v1/chats/:chat_id/messages status=201 response_bytes=219 latency=107.679µs
2026/10/06 19:21:16 request_id=2eb5822c-a9a8-468d-9ee9-0a1427103e0b method=POST path=/api/v1/chats/:chat_id/messages status=201 response_bytes=219 latency=99.848µs
2026/10/06 19:21:16 request_id=df851a12-561b-43c4-aab5-c52c5b3e0e2c method=POST path=/api/v1/chats/:chat_id/messages status=201 response_bytes=219 latency=83.018µs
2026/10/06 19:21:16 request_id=ed803853-7e7e-4f02-860f-8b7b5572fcf6 method=POST path=/api/v1/chats/:chat_id/messages status=201 response_bytes=219 latency=78.395µs
2026/10/06 19:21:16 request_id=baf94eab-e920-4b30-81f9-0220f59805e6 method=POST path=/api/v1/chats/:chat_id/messages status=201 response_bytes=219 latency=68.856µs
2026/10/06 19:21:16 request_id=16ce0479-c801-4b8f-9337-a9d18bcee63f method=POST path=/api/v1/chats/:chat_id/messages status=201 response_bytes=219 latency=85.893µs
2026/10/06 19:21:16 request_id=2615c1cb-0f70-48bc-9acf-2ce937498d73 method=POST path=/api/v1/chats/:chat_id/messages status=201 response_bytes=219 latency=73.23µs
2026/10/06 19:21:16 request_id=36ad82d0-c115-4470-9e03-e38808f12824 method=POST path=/api/v1/chats/:chat_id/messages status=201 response_bytes=219 latency=71.897µs
2026/10/06 19:21:16 request_id=adf59f98-ec84-4009-bb50-ae43e0bcf324 method=POST path=/api/v1/chats/:chat_id/messages status=201 response_bytes=219 latency=79.561µs
2026/10/06 19:21:16 request_id=55bfe8ac-2831-406a-aa6c-b8c3d4baed77 method=POST path=/api/v1/chats/:chat_id/messages status=201 response_bytes=219 latency=71.48µs
2026/10/06 19:21:16 request_id=d518730c-0e14-41f4-95cb-26dc33044604 method=POST path=/api/v1/chats/:chat_id/messages status=201 response_bytes=219 latency=388.1µs
2026/10/06 19:21:16 request_id=5c579f45-537c-4932-a180-ec4f15c9cf62 method=POST path=/api/v1/chats/:chat_id/messages status=201 response_bytes=219 latency=92.307µs
2026/10/06 19:21:16 request_id=503877f3-1f49-4f78-97b6-13b8a515784e method=POST path=/api/v1/chats/:chat_id/messages status=201 response_bytes=219 latency=82.852µs
2026/10/06 19:21:16 request_id=e78c8851-6ebb-44bb-b3a4-0f467ddea2d3 method=POST path=/api/v1/chats/:chat_id/messages status=201 response_bytes=219 latency=66.148µs
2026/10/06 19:21:16 request_id=26abe51e-6a5b-4de4-bff9-568119dea841 method=POST path=/api/v1/chats/:chat_id/messages status=201 response_bytes=219 latency=163.204µs
2026/10/06 19:21:16 request_id=bb21674c-6667-4568-ae90-9bd11fd0f7aa method=POST path=/api/v1/chats/:chat_id/messages status=201 response_bytes=219 latency=83.101µs
2026/10/06 19:21:16 request_id=fca9b5db-5dd3-41e9-a009-d63bd99e390e method=POST path=/api/v1/chats/:chat_id/messages status=201 response_bytes=219 latency=63.482µs
2026/10/06 19:21:16 request_id=ea93e3ec-a4cd-4af2-8578-9af84efe8e06 method=POST path=/api/v1/chats/:chat_id/messages status=201 response_bytes=219 latency=68.106µs
2026/10/06 19:21:16 request_id=6e8f78ab-b40f-48ba-a465-fc23e997e39e method=POST path=/api/v1/chats/:chat_id/messages status=201 response_bytes=219 latency=165.62µs
2026/10/06 19:21:16 request_id=b929f425-68d4-4972-ae17-eb4815e5d818 method=POST path=/api/v1/chats/:chat_id/messages status=201 response_bytes=219 latency=79.019µs
2026/10/06 19:21:16 request_id=58d53db6-b621-42e7-abfd-bd05146d6f21 method=POST path=/api/v1/chats/:chat_id/messages status=201 response_bytes=219 latency=66.44µs
2026/10/06 19:21:16 request_id=b6dda1b7-2bb7-4eff-b50b-7c25363ff30c method=POST path=/api/v1/chats/:chat_id/messages status=201 response_bytes=219 latency=69.397µs
2026/10/06 19:21:16 request_id=2a09a8fd-c2e4-4656-9326-b237f5c5977c method=POST path=/api/v1/chats/:chat_id/messages status=201 response_bytes=219 latency=72.188µs
2026/10/06 19:21:16 request_id=a67fc471-ce95-47db-aecc-42476f05c0b3 method=POST path=/api/v1/chats/:chat_id/messages status=201 response_bytes=219 latency=64.149µs
2026/10/06 19:21:16 request_id=22393415-489e-4ce2-a48a-6495d2e393c3 method=POST path=/api/v1/chats/:chat_id/messages status=201 response_bytes=219 latency=98.098µs
2026/10/06 19:21:16 request_id=2f3fa55a-3aa1-496c-b853-2e66bf8e9a76 method=POST path=/api/v1/chats/:chat_id/messages status=201 response_bytes=219 latency=137.295µs
2026/10/06 19:21:16 request_id=62f9409c-da83-415a-af67-ba4e39caaa2d method=POST path=/api/v1/chats/:chat_id/messages status=201 response_bytes=219 latency=65.649µs
2026/10/06 19:21:16 request_id=a282dd3c-eac5-4780-9648-3d63b60127be method=POST path=/api/v1/chats/:chat_id/messages status=201 response_bytes=219 latency=62.774µs
2026/10/06 19:21:16 request_id=d64a3337-41bf-4a70-a4ac-3f064f44efe3 method=POST path=/api/v1/chats/:chat_id/messages status=201 response_bytes=219 latency=326.742µs
2026/10/06 19:21:16 request_id=e0fb3964-01d6-4681-ae07-2434a344a637 method=POST path=/api/v1/chats/:chat_id/messages status=201 response_bytes=219 latency=69.48µs
2026/10/06 19:21:16 request_id=9f0e2f1f-d4d6-45b0-b39e-d1057ffefd53 method=POST path=/api/v1/chats/:chat_id/messages status=201 response_bytes=219 latency=63.357µs
2026/10/06 19:21:16 request_id=f0adaa9f-ca77-4578-ac3d-d807e44c643b method=POST path=/api/v1/chats/:chat_id/messages status=201 response_bytes=219 latency=75.229µs
2026/10/06 19:21:16 request_id=6b9fa169-a65d-447e-90b4-8cdd477c4db1 method=POST path=/api/v1/chats/:chat_id/messages status=201 response_bytes=219 latency=75.021µs
2026/10/06 19:21:16 request_id=bb200fb7-109f-4f29-b425-ead35d43b9f5 method=POST path=/api/v1/chats/:chat_id/messages status=201 response_bytes=219 latency=196.778µs
2026/10/06 19:21:16 request_id=7de12629-7c0f-4b4b-b179-f8b05a05e2a1 method=POST path=/api/v1/chats/:chat_id/messages status=201 response_bytes=219 latency=84.56µs
2026/10/06 19:21:16 request_id=c44c137f-b047-46b7-9cea-6742247b9f9b method=POST path=/api/v1/chats/:chat_id/messages status=201 response_bytes=219 latency=70.314µs
2026/10/06 19:21:16 request_id=5be496b4-f4d4-4c81-8834-7ef1f354143b method=POST path=/api/v1/chats/:chat_id/messages status=201 response_bytes=219 latency=105.095µs
2026/10/06 19:21:16 request_id=5a0f5f0f-57e4-4be4-9648-20d164bfacb2 method=POST path=/api/v1/chats/:chat_id/messages status=201 response_bytes=219 latency=500.193µs
2026/10/06 19:21:16 request_id=b0369f94-f269-4597-8f21-5b95b320c907 method=POST path=/api/v1/chats/:chat_id/messages status=201 response_bytes=219 latency=72.438µs
2026/10/06 19:21:16 request_id=49270a3b-8c25-4b38-81ac-949b770db00d method=POST path=/api/v1/chats/:chat_id/messages status=201 response_bytes=219 latency=263.718µs
2026/10/06 19:21:16 request_id=20dc5273-e236-4665-8d5a-c18e0e0cf704 method=POST path=/api/v1/chats/:chat_id/messages status=201 response_bytes=219 latency=166.786µs
2026/10/06 19:21:16 request_id=a0337f63-fb51-4d21-a2d3-e9fd9b66dfb0 method=POST path=/api/v1/chats/:chat_id/messages status=201 response_bytes=219 latency=135.503µs
2026/10/06 19:21:16 request_id=7b6f7175-37f3-4ae6-acf0-153e000c42b8 method=POST path=/api/v1/chats/:chat_id/messages status=201 response_bytes=219 latency=123.049µs
2026/10/06 19:21:16 request_id=f6ae7a25-2b42-4cbd-a81b-b4fc5e569b11 method=POST path=/api/v1/chats/:chat_id/messages status=201 response_bytes=219 latency=73.605µs
2026/10/06 19:21:16 request_id=5d0e62aa-05cc-44ea-ae25-adda74263b28 method=POST path=/api/v1/chats/:chat_id/messages status=201 response_bytes=219 latency=94.141µs
2026/10/06 19:21:16 request_id=6d9abca1-f328-4474-bcc0-2145cb473365 method=POST path=/api/v1/chats/:chat_id/messages status=201 response_bytes=219 latency=72.855µs
2026/10/06 19:21:16 request_id=f1d6de04-092a-440e-a8b6-09f9294086c4 method=POST path=/api/v1/chats/:chat_id/messages status=201 response_bytes=219 latency=81.936µs
2026/10/06 19:21:16 request_id=f456ab51-2d48-4698-970c-f33acbbd4773 method=POST path=/api/v1/chats/:chat_id/messages status=201 response_bytes=219 latency=67.356µs
2026/10/06 19:21:16 request_id=716607c6-2fdc-4284-98e3-6e313d00bc61 method=POST path=/api/v1/chats/:chat_id/messages status=201 response_bytes=219 latency=67.314µs
2026/10/06 19:21:16 request_id=412131fc-faac-454e-bfeb-0239b92c121f method=POST path=/api/v1/chats/:chat_id/messages status=201 response_bytes=219 latency=85.726µs
2026/10/06 19:21:16 request_id=4718c127-9794-4ad2-820e-6923267370a8 method=POST path=/api/v1/chats/:chat_id/messages status=201 response_bytes=219 latency=203.318µs
2026/10/06 19:21:16 request_id=f2a442a4-a087-403e-8d3a-d137f8c92506 method=POST path=/api/v1/chats/:chat_id/messages status=201 response_bytes=219 latency=84.976µs
2026/10/06 19:21:16 request_id=125a1d92-b797-4d3e-a43c-7abc31ab6ced method=POST path=/api/v1/chats/:chat_id/messages status=201 response_bytes=219 latency=70.23µs
2026/10/06 19:21:16 request_id=ebfff79b-7c13-4025-a0a7-84e3f161a58a method=POST path=/api/v1/chats/:chat_id/messages status=201 response_bytes=219 latency=153.54µs
2026/10/06 19:21:16 request_id=cf38fa2e-56c2-4c75-9dce-ea29535f92c1 method=POST path=/api/v1/chats/:chat_id/messages status=201 response_bytes=219 latency=131.755µs
2026/10/06 19:21:16 request_id=014731e1-156c-4f7d-8045-5eec3d214d7b method=POST path=/api/v1/chats/:chat_id/messages status=201 response_bytes=219 latency=143.793µs
2026/10/06 19:21:16 request_id=5df4970c-56bd-44d7-984a-b851bd4e886d method=POST path=/api/v1/chats/:chat_id/messages status=201 response_bytes=219 latency=73.813µs
2026/10/06 19:21:16 request_id=269aef01-c4f9-493e-8546-74af19ac949f method=POST path=/api/v1/chats/:chat_id/messages status=201 response_bytes=219 latency=90.35µs
2026/10/06 19:21:16 request_id=7a6522cc-7ac7-44ba-a2c7-fe06c06efac8 method=POST path=/api/v1/chats/:chat_id/messages status=201 response_bytes=219 latency=85.726µs
2026/10/06 19:21:16 request_id=c3ca99c2-0c5d-45d1-b0ac-c90c96072562 method=POST path=/api/v1/chats/:chat_id/messages status=201 response_bytes=219 latency=66.065µs
2026/10/06 19:21:16 request_id=56f4b1c0-1610-4d17-be0d-d827b2646779 method=POST path=/api/v1/chats/:chat_id/messages status=201 response_bytes=219 latency=119.175µs
2026/10/06 19:21:16 request_id=5369e115-0a39-423d-a4c3-911b5312847f method=POST path=/api/v1/chats/:chat_id/messages status=201 response_bytes=219 latency=76.229µs
2026/10/06 19:21:16 request_id=a23c450e-576f-4c20-a74a-45483327d88c method=POST path=/api/v1/chats/:chat_id/messages status=201 response_bytes=219 latency=115.259µs
2026/10/06 19:21:16 request_id=c288050a-bf02-4fbf-bf7a-d7f52ac8378f method=POST path=/api/v1/chats/:chat_id/messages status=201 response_bytes=219 latency=86.851µs
2026/10/06 19:21:16 request_id=5de59665-2ceb-4e7c-9e31-87c6ac9aa71c method=POST path=/api/v1/chats/:chat_id/messages status=201 response_bytes=219 latency=94.557µs
2026/10/06 19:21:16 request_id=b93979f5-b315-4187-a704-3279bcdc7d5f method=POST path=/api/v1/chats/:chat_id/messages status=201 response_bytes=219 latency=107.845µs
2026/10/06 19:21:16 request_id=6adfced1-f1da-4bcf-94d3-96d527d113d8 method=POST path=/api/v1/chats/:chat_id/messages status=201 response_bytes=219 latency=97.89µs
2026/10/06 19:21:16 request_id=a89fd3cb-7360-4001-ba32-b622c8acac11 method=POST path=/api/v1/chats/:chat_id/messages status=201 response_bytes=219 latency=69.022µs
2026/10/06 19:21:16 request_id=a39fde24-d1a3-4447-97d2-01bce7fe8979 method=POST path=/api/v1/chats/:chat_id/messages status=201 response_bytes=219 latency=74.771µs
2026/10/06 19:21:16 request_id=b10fc69b-9d83-48cb-a8c5-a8b0bd08241b method=POST path=/api/v1/chats/:chat_id/messages status=201 response_bytes=219 latency=93.89µs
2026/10/06 19:21:16 request_id=848e41f5-252b-4bf3-b6c9-5e117e9a9166 method=POST path=/api/v1/chats/:chat_id/messages status=201 response_bytes=219 latency=81.227µs
2026/10/06 19:21:16 request_id=d95a4100-40bc-468a-982c-45043938292c method=POST path=/api/v1/chats/:chat_id/messages status=201 response_bytes=219 latency=69.897µs
2026/10/06 19:21:16 request_id=790927d0-a008-478d-879d-f8dd3bd1e307 method=POST path=/api/v1/chats/:chat_id/messages status=201 response_bytes=219 latency=69.148µs
2026/10/06 19:21:16 request_id=fef3c11b-473c-4029-8a04-ab91e34fcb05 method=POST path=/api/v1/chats/:chat_id/messages status=201 response_bytes=219 latency=62.066µs
2026/10/06 19:21:16 request_id=172a30d2-7192-4340-b05a-1efa6753a205 method=POST path=/api/v1/chats/:chat_id/messages status=201 response_bytes=219 latency=61.816µs
2026/10/06 19:21:16 request_id=b72f998c-76db-4f94-a648-7872dbb21aa2 method=POST path=/api/v1/chats/:chat_id/messages status=201 response_bytes=219 latency=85.601µs
2026/10/06 19:21:16 request_id=18d3dd88-2424-41da-90ec-1c28a2068234 method=POST path=/api/v1/chats/:chat_id/messages status=201 response_bytes=219 latency=141.169µs
2026/10/06 19:21:16 request_id=a73c93b2-5ba9-4106-aaa8-115eccb5ba4c method=POST path=/api/v1/chats/:chat_id/messages status=201 response_bytes=219 latency=71.897µs
2026/10/06 19:21:16 request_id=25b35e42-2780-4dbf-b678-3fe047767ab9 method=POST path=/api/v1/chats/:chat_id/messages status=201 response_bytes=219 latency=103.096µs
2026/10/06 19:21:16 request_id=6700ff70-e182-41b8-94bf-bb98884d5cc0 method=POST path=/api/v1/chats/:chat_id/messages status=201 response_bytes=219 latency=74.854µs
2026/10/06 19:21:16 request_id=3f69dfda-66aa-4e38-a14f-bd60637e5795 method=POST path=/api/v1/chats/:chat_id/messages status=201 response_bytes=219 latency=71.396µs
2026/10/06 19:21:16 request_id=9ba1181d-c0ac-4eb6-a372-1056312ae6d5 method=POST path=/api/v1/chats/:chat_id/messages status=201 response_bytes=219 latency=66.815µs
2026/10/06 19:21:16 request_id=26577b5f-ca86-4cfb-abd3-2960b003c6b8 method=POST path=/api/v1/chats/:chat_id/messages status=201 response_bytes=219 latency=67.647µs
2026/10/06 19:21:16 request_id=ebfdbe7e-eb01-45a6-a5c3-3d57f15c8b29 method=POST path=/api/v1/chats/:chat_id/messages status=201 response_bytes=219 latency=94.682µs
2026/10/06 19:21:16 request_id=99b59a51-7316-45de-81af-789d3578ccf4 method=POST path=/api/v1/chats/:chat_id/messages status=201 response_bytes=219 latency=64.982µs
2026/10/06 19:21:16 request_id=a2405336-12b6-436c-b59b-fd9d0dadaf90 method=POST path=/api/v1/chats/:chat_id/messages status=201 response_bytes=219 latency=80.436µs
2026/10/06 19:21:16 request_id=f410744f-17f5-4b9f-ba88-407a3d1f7cb6 method=POST path=/api/v1/chats/:chat_id/messages status=201 response_bytes=219 latency=118.759µs
2026/10/06 19:21:16 request_id=660967af-2887-4231-8956-89d3dc80631a method=POST path=/api/v1/chats/:chat_id/messages status=201 response_bytes=219 latency=74.688µs
2026/10/06 19:21:16 request_id=b8a5b1e5-49fb-42bd-b20f-673073395516 method=POST path=/api/v1/chats/:chat_id/messages status=201 response_bytes=219 latency=84.101µs
2026/10/06 19:21:16 request_id=ca1d617b-c8b3-4186-b9e1-2611a1b54cb6 method=POST path=/api/v1/chats/:chat_id/messages status=201 response_bytes=219 latency=67.273µs
2026/10/06 19:21:16 request_id=1900187a-0eb9-4a92-b737-ad244582b2f7 method=POST path=/api/v1/chats/:chat_id/messages status=201 response_bytes=219 latency=64.607µs
2026/10/06 19:21:16 request_id=4e9d7855-4162-4cbd-b74d-25e40a615423 method=POST path=/api/v1/chats/:chat_id/messages status=201 response_bytes=219 latency=63.315µs
2026/10/06 19:21:16 request_id=18510d80-8a23-43aa-a8b1-df0a09ede963 method=POST path=/api/v1/chats/:chat_id/messages status=201 response_bytes=219 latency=65.19µs
2026/10/06 19:21:16 request_id=85c580e6-bd0a-4f8e-9db6-da3f4bd77d88 method=POST path=/api/v1/chats/:chat_id/messages status=201 response_bytes=219 latency=65.44µs
2026/10/06 19:21:16 request_id=248b2eb0-2ec8-4df5-9890-3965f013c9b9 method=POST path=/api/v1/chats/:chat_id/messages status=201 response_bytes=219 latency=61.024µs
2026/10/06 19:21:16 request_id=834ec62e-6398-4ec6-80b1-2ae581ed34cc method=POST path=/api/v1/chats/:chat_id/messages status=201 response_bytes=219 latency=62.191µs
2026/10/06 19:21:16 request_id=c015940c-08f0-45c7-af18-bd7d4f8f6205 method=POST path=/api/v1/chats/:chat_id/messages status=201 response_bytes=219 latency=57.526µs
2026/10/06 19:21:16 request_id=2ec696e9-c951-479d-a949-56c8b47f3579 method=POST path=/api/v1/chats/:chat_id/messages status=201 response_bytes=219 latency=79.603µs
2026/10/06 19:21:16 request_id=14d620cc-f9d9-4bc0-a366-1757bcb523e6 method=POST path=/api/v1/chats/:chat_id/messages status=201 response_bytes=219 latency=66.398µs
2026/10/06 19:21:16 request_id=ee6d1c5d-c70f-4e02-9ce6-cd379febfd39 method=POST path=/api/v1/chats/:chat_id/messages status=201 response_bytes=219 latency=73.604µs
2026/10/06 19:21:16 request_id=b06e4c73-f928-4db1-95b5-ecb65561b8d6 method=GET path=/api/v1/chats/:chat_id/messages status=200 response_bytes=3992 latency=561.259µs
2026/10/06 19:21:16 request_id=c658374a-4ad2-4fc3-b90d-a5eec1fab760 method=GET path=/api/v1/chats/:chat_id/messages status=200 response_bytes=3992 latency=592.751µs
2026/10/06 19:21:16 request_id=040d5c1b-ebb8-4777-8281-f5f9a6e33e33 method=GET path=/api/v1/chats/:chat_id/messages status=200 response_bytes=3992 latency=532.143µs
2026/10/06 19:21:16 request_id=7e8c90e6-9cc8-459a-898a-628797411b79 method=GET path=/api/v1/chats/:chat_id/messages status=200 response_bytes=3992 latency=545.681µs
2026/10/06 19:21:16 request_id=82b2c0b8-34c9-495b-9cd0-cf048732e163 method=GET path=/api/v1/chats/:chat_id/messages status=200 response_bytes=3992 latency=410.426µs
2026/10/06 19:21:16 request_id=9f4c48a4-b073-451d-ac6c-7f4bba303965 method=GET path=/api/v1/chats/:chat_id/messages status=200 response_bytes=3316 latency=303.831µs
--- PASS: TestConcurrentMessagesAreUnique (5.82s)
PASS
ok gitflic.ru/akselbant/mtusi2026lab1-fork/internal/app/chat 10.086s
? gitflic.ru/akselbant/mtusi2026lab1-fork/internal/config [no test files]
? gitflic.ru/akselbant/mtusi2026lab1-fork/internal/pkg/domain [no test files]
=== RUN TestUnicodeAndSalt
--- PASS: TestUnicodeAndSalt (1.77s)
PASS
ok gitflic.ru/akselbant/mtusi2026lab1-fork/internal/pkg/password 2.805s
? gitflic.ru/akselbant/mtusi2026lab1-fork/internal/pkg/repository [no test files]
=== RUN TestIntegration
storage_test.go:84: goose up: 2026/10/06 19:21:21 OK 001_initial.sql (12.05ms)
2026/10/06 19:21:21 goose: successfully migrated database to version: 1
storage_test.go:85: goose up: 2026/10/06 19:21:21 goose: no migrations to run. current version: 1
=== RUN TestIntegration/registration_race
storage_test.go:121: 12 concurrent INSERTs: 1 success, 11 unique conflicts
=== RUN TestIntegration/rollback
storage_test.go:139: failed second member INSERT left 0 chats and 0 members
=== RUN TestIntegration/keyset_and_explain
storage_test.go:186: EXPLAIN on 10,000 messages, cursor near the end (9,000):
storage_test.go:192: Limit (cost=0.29..16.15 rows=51 width=142) (actual time=0.011..0.026 rows=51 loops=1)
storage_test.go:192: Buffers: shared hit=5
storage_test.go:192: -> Index Scan using messages_history_idx on messages m (cost=0.29..311.35 rows=1000 width=142) (actual time=0.011..0.023 rows=51 loops=1)
storage_test.go:192: Index Cond: ((chat_id = '2cd3eb66-3ffd-4d6c-9c0c-c4f82aaabdc4'::uuid) AND (ROW(created_at, id) > ROW('2026-01-01 00:00:00.9+00'::timestamp with time zone, '00000000-0000-0000-0000-000000000000'::uuid)))
storage_test.go:192: Buffers: shared hit=5
storage_test.go:192: Planning Time: 0.047 ms
storage_test.go:192: Execution Time: 0.044 ms
storage_test.go:197: keyset traversal returned 10,000 distinct messages, including equal timestamps
=== RUN TestIntegration/goose_legacy_and_down
storage_test.go:211: goose up: 2026/10/06 19:21:21 OK 001_initial.sql (1.91ms)
2026/10/06 19:21:21 goose: successfully migrated database to version: 1
storage_test.go:212: goose up: 2026/10/06 19:21:21 goose: no migrations to run. current version: 1
storage_test.go:219: adopted legacy schema: all 10,000 messages are unchanged
storage_test.go:220: goose down: 2026/10/06 19:21:21 OK 001_initial.sql (10.84ms)
storage_test.go:225: goose up: 2026/10/06 19:21:21 OK 001_initial.sql (11.27ms)
2026/10/06 19:21:21 goose: successfully migrated database to version: 1
storage_test.go:229: down and up succeeded in isolated schema
--- PASS: TestIntegration (0.47s)
--- PASS: TestIntegration/registration_race (0.03s)
--- PASS: TestIntegration/rollback (0.00s)
--- PASS: TestIntegration/keyset_and_explain (0.06s)
--- PASS: TestIntegration/goose_legacy_and_down (0.10s)
PASS
ok gitflic.ru/akselbant/mtusi2026lab1-fork/internal/pkg/repository/postgres 1.491s
? gitflic.ru/akselbant/mtusi2026lab1-fork/internal/pkg/session [no test files]
=== RUN TestPasswordContract
--- PASS: TestPasswordContract (0.00s)
PASS
ok gitflic.ru/akselbant/mtusi2026lab1-fork/internal/usecase/chat 1.012s
+3
View File
@@ -0,0 +1,3 @@
python3 tests/resilience.py --mode persistence --action-script "scripts/restart.sh" --base-url "http://localhost:8080"
Executing explicit persistence hook; hook output suppressed to avoid leaking secrets.
PASS: persistence preserved confirmed data and existing session. Hook scope needs operator evidence.
+3
View File
@@ -0,0 +1,3 @@
PASS: switching the existing stack to goose preserved the existing session and confirmed message.
migrations-1 | 2026/10/06 19:19:45 OK 001_initial.sql (11.47ms)
migrations-1 | 2026/10/06 19:19:45 goose: successfully migrated database to version: 1
+9
View File
@@ -0,0 +1,9 @@
python3 tests/own/grade4.py
PASS: wrong password, unknown user, Bearer-only access, X-User-Id ignored, logout
PASS: 128-code-point Unicode password including colon; suffix verified
PASS: HTTP registration race: one 201, seven 409
PASS: redis outage bounded; live=200, ready=503, protected=503, anonymous=401; session recovered, logout retained
PASS: postgres outage bounded; live=200, ready=503, protected=503, anonymous=401; session recovered, logout retained
PASS: cursor and existing session survive API restart
PASS: SESSION_TTL_SECONDS=2 expires; Redis restart does not revive expired session
PASS: all grade-4 HTTP checks; normal TTL restored to 3600
+208
View File
@@ -0,0 +1,208 @@
Command: make test-integration PORT=8080
Go 1.26.4 linux/arm64; go test -p=1 -race -count=1 -v ./...
? gitflic.ru/akselbant/mtusi2026lab1-fork/cmd [no test files]
? gitflic.ru/akselbant/mtusi2026lab1-fork/contracts [no test files]
=== RUN TestTimestampFixedMicroseconds
--- PASS: TestTimestampFixedMicroseconds (0.00s)
PASS
ok gitflic.ru/akselbant/mtusi2026lab1-fork/dto 1.013s
=== RUN TestRejectsMalformedJSON
2026/10/06 17:11:46 request_id=e8e4c5cb-9f29-4417-90c9-6c6bb7fbf87b method=POST path=/api/v1/users status=400 response_bytes=140 latency=124.462µs
--- PASS: TestRejectsMalformedJSON (0.00s)
=== RUN TestHidesForeignChat
2026/10/06 17:11:46 request_id=59f8e8c9-bdf7-4ae9-b54e-a03228cfb388 method=POST path=/api/v1/users status=201 response_bytes=141 latency=279.803447ms
2026/10/06 17:11:46 request_id=76453c2a-45f0-4d7e-b3c2-a7fb08b5e149 method=POST path=/api/v1/auth/sessions status=201 response_bytes=269 latency=277.437307ms
2026/10/06 17:11:47 request_id=36e8af31-56ea-4032-8307-4e0ee0ac9f32 method=POST path=/api/v1/users status=201 response_bytes=147 latency=275.096835ms
2026/10/06 17:11:47 request_id=359f9f08-2e2d-4ca5-b5fb-e8f6c028a613 method=POST path=/api/v1/auth/sessions status=201 response_bytes=275 latency=268.544894ms
2026/10/06 17:11:47 request_id=870c9c2c-56d3-47e0-a609-e57f8c89a111 method=POST path=/api/v1/chats status=201 response_bytes=163 latency=145.171µs
2026/10/06 17:11:47 request_id=80336c91-4039-4ccb-8a52-84c8425b91af method=GET path=/api/v1/chats/:chat_id status=404 response_bytes=126 latency=42.418µs
--- PASS: TestHidesForeignChat (1.11s)
=== RUN TestRejectsEmptyMessage
2026/10/06 17:11:47 request_id=ca62f6b7-5d96-480c-99c6-606060bd3036 method=POST path=/api/v1/users status=201 response_bytes=157 latency=265.214939ms
2026/10/06 17:11:47 request_id=743e15b0-26ff-4887-b5ec-b6b90c7b2af7 method=POST path=/api/v1/auth/sessions status=201 response_bytes=285 latency=274.81692ms
2026/10/06 17:11:47 request_id=ad65e486-2554-4545-b231-7ba0339af859 method=POST path=/api/v1/chats status=201 response_bytes=163 latency=87.752µs
2026/10/06 17:11:47 request_id=02390097-3490-4607-9542-20836f022f73 method=POST path=/api/v1/chats/:chat_id/messages status=400 response_bytes=172 latency=96.669µs
--- PASS: TestRejectsEmptyMessage (0.54s)
=== RUN TestRejectsDuplicateUsername
2026/10/06 17:11:48 request_id=fd31a2dc-266f-4755-aa48-2eaae0ba62d6 method=POST path=/api/v1/users status=201 response_bytes=149 latency=264.826517ms
2026/10/06 17:11:48 request_id=e91002ae-4e94-4eda-8cd5-5c0954a8ed29 method=POST path=/api/v1/auth/sessions status=201 response_bytes=277 latency=276.543262ms
2026/10/06 17:11:48 request_id=ca219059-0e42-49ff-b178-455b4ca73ba2 method=POST path=/api/v1/users status=409 response_bytes=170 latency=264.399928ms
--- PASS: TestRejectsDuplicateUsername (0.81s)
=== RUN TestPaginatesMessagesAcrossMultiplePages
2026/10/06 17:11:48 request_id=76e157d8-745c-48ca-aca8-50876bbaed94 method=POST path=/api/v1/users status=201 response_bytes=151 latency=265.669625ms
2026/10/06 17:11:49 request_id=142854de-61a6-4dca-ac97-d051fc005f36 method=POST path=/api/v1/auth/sessions status=201 response_bytes=279 latency=277.875757ms
2026/10/06 17:11:49 request_id=6fe0c262-da8f-4a93-8974-5c7eac622c48 method=POST path=/api/v1/chats status=201 response_bytes=163 latency=93.544µs
2026/10/06 17:11:49 request_id=7b9bb503-672b-458b-a208-3368280d9b5d method=POST path=/api/v1/chats/:chat_id/messages status=201 response_bytes=208 latency=108.169µs
2026/10/06 17:11:49 request_id=7795d082-8517-4111-bd1c-2c73107f8f99 method=POST path=/api/v1/chats/:chat_id/messages status=201 response_bytes=208 latency=86.543µs
2026/10/06 17:11:49 request_id=625b8a36-e94c-4cb8-80b7-ab61aef8d9d5 method=POST path=/api/v1/chats/:chat_id/messages status=201 response_bytes=208 latency=71.294µs
2026/10/06 17:11:49 request_id=aaf9c35f-c9db-42f3-b670-5c82101b39fe method=POST path=/api/v1/chats/:chat_id/messages status=201 response_bytes=208 latency=71.46µs
2026/10/06 17:11:49 request_id=f1a49f33-6985-475d-a28c-155484a01609 method=POST path=/api/v1/chats/:chat_id/messages status=201 response_bytes=208 latency=79.919µs
2026/10/06 17:11:49 request_id=a69e732c-7059-4933-95ef-e508e282cc2b method=POST path=/api/v1/chats/:chat_id/messages status=201 response_bytes=208 latency=68.169µs
2026/10/06 17:11:49 request_id=715a0198-b00b-48c4-bc53-e267037bf35a method=POST path=/api/v1/chats/:chat_id/messages status=201 response_bytes=208 latency=71.669µs
2026/10/06 17:11:49 request_id=c5eb79fb-9fe3-41ac-b5d1-66a170eec00e method=GET path=/api/v1/chats/:chat_id/messages status=200 response_bytes=685 latency=253.048µs
2026/10/06 17:11:49 request_id=05754f2f-26b7-4b6b-9926-0aa40c70076b method=GET path=/api/v1/chats/:chat_id/messages status=200 response_bytes=685 latency=148.711µs
2026/10/06 17:11:49 request_id=25609aab-fb9a-44d0-be3e-c99e1056d5c5 method=GET path=/api/v1/chats/:chat_id/messages status=200 response_bytes=685 latency=136.462µs
2026/10/06 17:11:49 request_id=e3f7546e-3e35-4c22-bf83-2eb9eee5f7d3 method=GET path=/api/v1/chats/:chat_id/messages status=200 response_bytes=239 latency=84.211µs
--- PASS: TestPaginatesMessagesAcrossMultiplePages (0.55s)
=== RUN TestConcurrentMessagesAreUnique
2026/10/06 17:11:49 request_id=6af0ec62-1457-4017-a334-8b61a6dd8523 method=POST path=/api/v1/users status=201 response_bytes=153 latency=263.137073ms
2026/10/06 17:11:49 request_id=40bdce31-ceb4-46bd-bb25-b101ecf89310 method=POST path=/api/v1/auth/sessions status=201 response_bytes=281 latency=272.859849ms
2026/10/06 17:11:49 request_id=88d9f958-2a70-4cd3-bad7-d1f68158922f method=POST path=/api/v1/users status=201 response_bytes=153 latency=265.578006ms
2026/10/06 17:11:50 request_id=dbefec27-8f9f-436c-9ff1-14b8befe470c method=POST path=/api/v1/auth/sessions status=201 response_bytes=281 latency=270.656678ms
2026/10/06 17:11:50 request_id=94288b11-d077-4e75-b2e3-3cc66a1a9b73 method=POST path=/api/v1/users status=201 response_bytes=153 latency=270.490758ms
2026/10/06 17:11:50 request_id=75e67e24-6021-46a2-8d39-c74fc75276a2 method=POST path=/api/v1/auth/sessions status=201 response_bytes=281 latency=281.818072ms
2026/10/06 17:11:51 request_id=208e2c45-b1cc-44b6-a42b-38c849cc5cb4 method=POST path=/api/v1/users status=201 response_bytes=153 latency=270.711933ms
2026/10/06 17:11:51 request_id=5c862fa9-3148-4c57-bd0f-5c546b75a97b method=POST path=/api/v1/auth/sessions status=201 response_bytes=281 latency=267.219479ms
2026/10/06 17:11:51 request_id=d3ccd7ab-daf6-4e16-98b1-db63f6bc2521 method=POST path=/api/v1/users status=201 response_bytes=153 latency=267.147394ms
2026/10/06 17:11:51 request_id=8ee10021-c90d-4489-97e7-6338e43876ef method=POST path=/api/v1/auth/sessions status=201 response_bytes=281 latency=274.15848ms
2026/10/06 17:11:52 request_id=18bfdfa8-d107-4c10-82b8-8dd4ee0b8207 method=POST path=/api/v1/users status=201 response_bytes=153 latency=264.684298ms
2026/10/06 17:11:52 request_id=cf129218-f444-4af0-870b-05b75bbb1495 method=POST path=/api/v1/auth/sessions status=201 response_bytes=281 latency=277.132935ms
2026/10/06 17:11:52 request_id=45915a5a-a39b-46e0-abc2-e63df81acde5 method=POST path=/api/v1/users status=201 response_bytes=153 latency=267.330115ms
2026/10/06 17:11:52 request_id=7e6942c3-081b-415b-b67b-91a7ca8f1d7b method=POST path=/api/v1/auth/sessions status=201 response_bytes=281 latency=266.56843ms
2026/10/06 17:11:53 request_id=d1d60fa6-50ec-48d7-9062-e74946c1f573 method=POST path=/api/v1/users status=201 response_bytes=153 latency=265.348949ms
2026/10/06 17:11:53 request_id=11c9cd05-8fb2-4f47-8219-5160e6654878 method=POST path=/api/v1/auth/sessions status=201 response_bytes=281 latency=268.274729ms
2026/10/06 17:11:53 request_id=c4f12bba-e149-4e5f-80c9-ceab986465f5 method=POST path=/api/v1/users status=201 response_bytes=153 latency=273.191556ms
2026/10/06 17:11:54 request_id=8a80001d-9ce6-4fc3-9175-51b0b38e2fa8 method=POST path=/api/v1/auth/sessions status=201 response_bytes=281 latency=282.344697ms
2026/10/06 17:11:54 request_id=6b7f32c1-76ec-4e70-adf1-0be9971a568e method=POST path=/api/v1/users status=201 response_bytes=153 latency=269.452391ms
2026/10/06 17:11:54 request_id=20347766-723a-456a-8248-1addc0f0ba33 method=POST path=/api/v1/auth/sessions status=201 response_bytes=281 latency=320.228994ms
2026/10/06 17:11:54 request_id=65c95f19-d84f-480f-9fc7-9bf9714fec02 method=POST path=/api/v1/chats status=201 response_bytes=514 latency=185.922µs
2026/10/06 17:11:54 request_id=a3bb82a2-58c9-4cc0-bcf6-53e5008afebf method=POST path=/api/v1/chats/:chat_id/messages status=201 response_bytes=219 latency=137.128µs
2026/10/06 17:11:54 request_id=52ca4f8b-0abc-46df-95b0-bc82286f4c71 method=POST path=/api/v1/chats/:chat_id/messages status=201 response_bytes=219 latency=119.169µs
2026/10/06 17:11:54 request_id=d288240d-7bb6-4dd9-9f34-e2e96c580c5c method=POST path=/api/v1/chats/:chat_id/messages status=201 response_bytes=219 latency=117.377µs
2026/10/06 17:11:54 request_id=6373cde3-3649-4bec-906d-948dc0200ebe method=POST path=/api/v1/chats/:chat_id/messages status=201 response_bytes=219 latency=128.337µs
2026/10/06 17:11:54 request_id=92ad24c9-0420-4332-a057-4a9c1817c757 method=POST path=/api/v1/chats/:chat_id/messages status=201 response_bytes=219 latency=156.837µs
2026/10/06 17:11:54 request_id=a04edc1d-986f-4b3c-a21f-ef1672d6284c method=POST path=/api/v1/chats/:chat_id/messages status=201 response_bytes=219 latency=247.923µs
2026/10/06 17:11:54 request_id=48824c02-bf42-47ac-b11b-7f18ef79ee6a method=POST path=/api/v1/chats/:chat_id/messages status=201 response_bytes=219 latency=137.753µs
2026/10/06 17:11:54 request_id=42c76b98-b7f4-4b91-a6ff-47839ae45474 method=POST path=/api/v1/chats/:chat_id/messages status=201 response_bytes=219 latency=94.544µs
2026/10/06 17:11:54 request_id=9425866d-9655-4c71-bf27-1767f1db44fd method=POST path=/api/v1/chats/:chat_id/messages status=201 response_bytes=219 latency=106.294µs
2026/10/06 17:11:54 request_id=06805015-e5b9-4589-878d-181b6dd785da method=POST path=/api/v1/chats/:chat_id/messages status=201 response_bytes=219 latency=84.544µs
2026/10/06 17:11:54 request_id=bc858f79-d973-48ba-a883-73dabc9aa4af method=POST path=/api/v1/chats/:chat_id/messages status=201 response_bytes=219 latency=76.335µs
2026/10/06 17:11:54 request_id=0d713e11-b13b-4b44-89d9-ce5604adee7b method=POST path=/api/v1/chats/:chat_id/messages status=201 response_bytes=219 latency=91.002µs
2026/10/06 17:11:54 request_id=a691618a-47e4-4aed-947d-dad401e352f3 method=POST path=/api/v1/chats/:chat_id/messages status=201 response_bytes=219 latency=152.378µs
2026/10/06 17:11:54 request_id=ccfb2f60-7a13-4e9a-b1cd-69f0d7ce51b0 method=POST path=/api/v1/chats/:chat_id/messages status=201 response_bytes=219 latency=103.336µs
2026/10/06 17:11:54 request_id=36302370-157c-4d25-a61e-64b94c3b26f4 method=POST path=/api/v1/chats/:chat_id/messages status=201 response_bytes=219 latency=99.877µs
2026/10/06 17:11:54 request_id=a29fd9fc-201a-48a9-a3f7-a45cc0a3f6cd method=POST path=/api/v1/chats/:chat_id/messages status=201 response_bytes=219 latency=76.961µs
2026/10/06 17:11:54 request_id=a448c1c3-a88d-4de5-a20e-add6d4b04254 method=POST path=/api/v1/chats/:chat_id/messages status=201 response_bytes=219 latency=87.169µs
2026/10/06 17:11:54 request_id=7c1cdc74-3310-498f-9a4a-bd4a82b3a848 method=POST path=/api/v1/chats/:chat_id/messages status=201 response_bytes=219 latency=321.216µs
2026/10/06 17:11:54 request_id=f9a116fa-1dc4-4918-a2a6-28445db70b76 method=POST path=/api/v1/chats/:chat_id/messages status=201 response_bytes=219 latency=109.128µs
2026/10/06 17:11:54 request_id=4add97c2-9ff6-435f-8da8-946f174baf35 method=POST path=/api/v1/chats/:chat_id/messages status=201 response_bytes=219 latency=92.752µs
2026/10/06 17:11:54 request_id=8725e62e-2dec-4dcb-bd7b-b0f0f1063f26 method=POST path=/api/v1/chats/:chat_id/messages status=201 response_bytes=219 latency=171.046µs
2026/10/06 17:11:54 request_id=38dfbed6-1f66-4185-a739-a6b6014b0bf4 method=POST path=/api/v1/chats/:chat_id/messages status=201 response_bytes=219 latency=90.335µs
2026/10/06 17:11:54 request_id=e681db73-fffe-42f5-a965-89c4eab1c9c7 method=POST path=/api/v1/chats/:chat_id/messages status=201 response_bytes=219 latency=98.253µs
2026/10/06 17:11:54 request_id=6396166a-f0de-4275-a748-ee94704e7143 method=POST path=/api/v1/chats/:chat_id/messages status=201 response_bytes=219 latency=154.378µs
2026/10/06 17:11:54 request_id=b6f24d9f-4c61-4cec-8189-a0f78d95ed6a method=POST path=/api/v1/chats/:chat_id/messages status=201 response_bytes=219 latency=119.169µs
2026/10/06 17:11:54 request_id=fa6ed21a-d363-40b7-947e-fc5f2d09671e method=POST path=/api/v1/chats/:chat_id/messages status=201 response_bytes=219 latency=93.793µs
2026/10/06 17:11:54 request_id=f1e07424-0a84-45a2-a9e2-fa8269dc30e1 method=POST path=/api/v1/chats/:chat_id/messages status=201 response_bytes=219 latency=115.42µs
2026/10/06 17:11:54 request_id=8a69a804-d13b-420c-b116-9607897241d5 method=POST path=/api/v1/chats/:chat_id/messages status=201 response_bytes=219 latency=130.211µs
2026/10/06 17:11:54 request_id=fb35a833-deb8-4b84-acef-e96c3d41e243 method=POST path=/api/v1/chats/:chat_id/messages status=201 response_bytes=219 latency=77.961µs
2026/10/06 17:11:54 request_id=501bbc6d-db8e-4227-8e40-119357f0113f method=POST path=/api/v1/chats/:chat_id/messages status=201 response_bytes=219 latency=103.377µs
2026/10/06 17:11:54 request_id=8d6f6962-0ffc-4d3c-8da7-3ab412eb2403 method=POST path=/api/v1/chats/:chat_id/messages status=201 response_bytes=219 latency=77.794µs
2026/10/06 17:11:54 request_id=25e8c17c-c570-4017-be2e-bfd34a9f2914 method=POST path=/api/v1/chats/:chat_id/messages status=201 response_bytes=219 latency=71.543µs
2026/10/06 17:11:54 request_id=15e4bf7b-aba0-4260-bd35-8dfc9e3cf73c method=POST path=/api/v1/chats/:chat_id/messages status=201 response_bytes=219 latency=92.044µs
2026/10/06 17:11:54 request_id=9643a4c3-e680-4cc8-a11b-c2c9c3d01390 method=POST path=/api/v1/chats/:chat_id/messages status=201 response_bytes=219 latency=221.13µs
2026/10/06 17:11:54 request_id=b595eab1-ccc0-4053-86e3-195354c25808 method=POST path=/api/v1/chats/:chat_id/messages status=201 response_bytes=219 latency=102.752µs
2026/10/06 17:11:54 request_id=bf93fb32-5453-496c-8649-a50a6209c9dd method=POST path=/api/v1/chats/:chat_id/messages status=201 response_bytes=219 latency=74.751µs
2026/10/06 17:11:54 request_id=e53e255f-b83f-4397-a1b2-0113bb1b97c4 method=POST path=/api/v1/chats/:chat_id/messages status=201 response_bytes=219 latency=84.335µs
2026/10/06 17:11:54 request_id=9e456f89-82b6-468d-9186-d7ec6efeb9ae method=POST path=/api/v1/chats/:chat_id/messages status=201 response_bytes=219 latency=70.752µs
2026/10/06 17:11:54 request_id=12156394-5251-4e84-8818-1255da679988 method=POST path=/api/v1/chats/:chat_id/messages status=201 response_bytes=219 latency=82.877µs
2026/10/06 17:11:54 request_id=c31e88d2-66e7-41ec-b4c8-7e8da8d39b95 method=POST path=/api/v1/chats/:chat_id/messages status=201 response_bytes=219 latency=81.544µs
2026/10/06 17:11:54 request_id=baeff5ed-e644-4f26-8510-5d8cd396eff4 method=POST path=/api/v1/chats/:chat_id/messages status=201 response_bytes=219 latency=172.212µs
2026/10/06 17:11:54 request_id=052c42d3-fe16-4752-aeae-1ae44c6dc343 method=POST path=/api/v1/chats/:chat_id/messages status=201 response_bytes=219 latency=93.961µs
2026/10/06 17:11:54 request_id=77d17d31-9435-4579-8cd5-5b158b1c0516 method=POST path=/api/v1/chats/:chat_id/messages status=201 response_bytes=219 latency=96.044µs
2026/10/06 17:11:54 request_id=9b0408d1-7595-4574-996e-1bce95fb38d9 method=POST path=/api/v1/chats/:chat_id/messages status=201 response_bytes=219 latency=165.379µs
2026/10/06 17:11:54 request_id=0d06a023-2ee3-4f79-b900-d6538bbd25e2 method=POST path=/api/v1/chats/:chat_id/messages status=201 response_bytes=219 latency=76.335µs
2026/10/06 17:11:54 request_id=15cd3dea-8163-49d6-9680-cdb5e2b579c5 method=POST path=/api/v1/chats/:chat_id/messages status=201 response_bytes=219 latency=80.544µs
2026/10/06 17:11:54 request_id=33558c8f-4736-4fe9-8c19-98eaab6a6af9 method=POST path=/api/v1/chats/:chat_id/messages status=201 response_bytes=219 latency=83.752µs
2026/10/06 17:11:54 request_id=9c5c3195-6f95-4e81-901e-022b935e367b method=POST path=/api/v1/chats/:chat_id/messages status=201 response_bytes=219 latency=72.835µs
2026/10/06 17:11:54 request_id=78f77269-c519-4b88-9734-2735260561f2 method=POST path=/api/v1/chats/:chat_id/messages status=201 response_bytes=219 latency=479.553µs
2026/10/06 17:11:54 request_id=aae08242-deff-4334-b5ed-ec23283e69b1 method=POST path=/api/v1/chats/:chat_id/messages status=201 response_bytes=219 latency=364.259µs
2026/10/06 17:11:54 request_id=a53ea283-2125-4ee7-8bfb-fd81074a2def method=POST path=/api/v1/chats/:chat_id/messages status=201 response_bytes=219 latency=332.549µs
2026/10/06 17:11:54 request_id=060b42d9-8666-4b04-8473-7677adb2e047 method=POST path=/api/v1/chats/:chat_id/messages status=201 response_bytes=219 latency=469.345µs
2026/10/06 17:11:54 request_id=c64e9c1f-5a28-4d84-b876-9e121dd91d0c method=POST path=/api/v1/chats/:chat_id/messages status=201 response_bytes=219 latency=392.926µs
2026/10/06 17:11:54 request_id=c69ff53d-f60a-410e-b1ca-3ece4f4a3fb1 method=POST path=/api/v1/chats/:chat_id/messages status=201 response_bytes=219 latency=1.854545ms
2026/10/06 17:11:54 request_id=37b591e0-db2e-4c13-b780-c5b965f3a992 method=POST path=/api/v1/chats/:chat_id/messages status=201 response_bytes=219 latency=536.471µs
2026/10/06 17:11:54 request_id=786349e2-75a0-49f5-ab17-050099850eb5 method=POST path=/api/v1/chats/:chat_id/messages status=201 response_bytes=219 latency=1.776043ms
2026/10/06 17:11:54 request_id=e03250f7-1421-4b5b-ae20-1b7abd0f48fa method=POST path=/api/v1/chats/:chat_id/messages status=201 response_bytes=219 latency=3.066699ms
2026/10/06 17:11:54 request_id=b8240c72-52df-4930-80e4-a18909b0d0d2 method=POST path=/api/v1/chats/:chat_id/messages status=201 response_bytes=219 latency=2.881361ms
2026/10/06 17:11:54 request_id=0580b9b3-96e9-431b-8891-95b0cebbfee9 method=POST path=/api/v1/chats/:chat_id/messages status=201 response_bytes=219 latency=177.796µs
2026/10/06 17:11:54 request_id=08f73860-665e-495e-a519-16909f9f5cbb method=POST path=/api/v1/chats/:chat_id/messages status=201 response_bytes=219 latency=3.113742ms
2026/10/06 17:11:54 request_id=09ac1ec7-5759-4abc-a45c-05c731978b0b method=POST path=/api/v1/chats/:chat_id/messages status=201 response_bytes=219 latency=3.30783ms
2026/10/06 17:11:54 request_id=a73784b7-6e30-4cfa-aa2e-f51edc83d5a0 method=POST path=/api/v1/chats/:chat_id/messages status=201 response_bytes=219 latency=1.839045ms
2026/10/06 17:11:54 request_id=91ff10f9-ebf4-495d-974c-c75a03d44e36 method=POST path=/api/v1/chats/:chat_id/messages status=201 response_bytes=219 latency=107.419µs
2026/10/06 17:11:54 request_id=de529d6b-96d9-4629-a2b7-ead508a6fbeb method=POST path=/api/v1/chats/:chat_id/messages status=201 response_bytes=219 latency=238.631µs
2026/10/06 17:11:54 request_id=eabb36ab-882e-4020-905f-7eff28b1b64e method=POST path=/api/v1/chats/:chat_id/messages status=201 response_bytes=219 latency=80.586µs
2026/10/06 17:11:54 request_id=0c78dbfc-9262-4167-9830-beab61b92d83 method=POST path=/api/v1/chats/:chat_id/messages status=201 response_bytes=219 latency=77.752µs
2026/10/06 17:11:54 request_id=82083f7f-a6ba-4251-9beb-6672b358d001 method=POST path=/api/v1/chats/:chat_id/messages status=201 response_bytes=219 latency=84.169µs
2026/10/06 17:11:54 request_id=0798917d-7f68-43df-8012-d3592758615e method=POST path=/api/v1/chats/:chat_id/messages status=201 response_bytes=219 latency=137.587µs
2026/10/06 17:11:54 request_id=12388de4-e498-4b43-b452-3eddf22bb72c method=POST path=/api/v1/chats/:chat_id/messages status=201 response_bytes=219 latency=76.169µs
2026/10/06 17:11:54 request_id=cf93820f-2121-436b-8224-ba98b7ccb3e5 method=POST path=/api/v1/chats/:chat_id/messages status=201 response_bytes=219 latency=139.878µs
2026/10/06 17:11:54 request_id=e981d9b3-1aa1-49e7-8f59-9088e067a752 method=POST path=/api/v1/chats/:chat_id/messages status=201 response_bytes=219 latency=80.085µs
2026/10/06 17:11:54 request_id=ec1e6972-4109-4a64-aea7-bc739e358de7 method=POST path=/api/v1/chats/:chat_id/messages status=201 response_bytes=219 latency=142.67µs
2026/10/06 17:11:54 request_id=d43133b2-5393-4e9d-8970-1621d5bd6516 method=POST path=/api/v1/chats/:chat_id/messages status=201 response_bytes=219 latency=143.296µs
2026/10/06 17:11:54 request_id=77b37921-3954-4c9b-b338-1ca2128adb4b method=POST path=/api/v1/chats/:chat_id/messages status=201 response_bytes=219 latency=87.628µs
2026/10/06 17:11:54 request_id=50f3d8f8-167f-4bc6-9edc-4988f7adc463 method=POST path=/api/v1/chats/:chat_id/messages status=201 response_bytes=219 latency=183.296µs
2026/10/06 17:11:54 request_id=06e465be-61bb-423b-b116-ad6c67060bca method=POST path=/api/v1/chats/:chat_id/messages status=201 response_bytes=219 latency=90.669µs
2026/10/06 17:11:54 request_id=ca62fba6-b8ff-41c3-9ec9-f945d90f8be2 method=POST path=/api/v1/chats/:chat_id/messages status=201 response_bytes=219 latency=75.377µs
2026/10/06 17:11:54 request_id=45c86cde-f10b-4397-bb57-c991ab2a6afb method=POST path=/api/v1/chats/:chat_id/messages status=201 response_bytes=219 latency=92.335µs
2026/10/06 17:11:54 request_id=1ef6c336-3752-463f-9680-9985ea3839a5 method=POST path=/api/v1/chats/:chat_id/messages status=201 response_bytes=219 latency=83.502µs
2026/10/06 17:11:54 request_id=00adcb49-041e-482b-b7d1-624d5af93e19 method=POST path=/api/v1/chats/:chat_id/messages status=201 response_bytes=219 latency=89.21µs
2026/10/06 17:11:54 request_id=82bb2532-949a-4d96-9556-bbf806e909db method=POST path=/api/v1/chats/:chat_id/messages status=201 response_bytes=219 latency=78.127µs
2026/10/06 17:11:54 request_id=051999f5-8e23-44e8-9b6e-0d84594136e6 method=POST path=/api/v1/chats/:chat_id/messages status=201 response_bytes=219 latency=82.252µs
2026/10/06 17:11:54 request_id=e2984eab-756e-4b2d-ad4d-21f91e6670fe method=POST path=/api/v1/chats/:chat_id/messages status=201 response_bytes=219 latency=74.96µs
2026/10/06 17:11:54 request_id=da5c6ffa-2949-44d7-9c7d-3226d4644b02 method=POST path=/api/v1/chats/:chat_id/messages status=201 response_bytes=219 latency=161.087µs
2026/10/06 17:11:54 request_id=f4bfdf94-7888-42d9-987c-c5553c80e2a4 method=POST path=/api/v1/chats/:chat_id/messages status=201 response_bytes=219 latency=64.71µs
2026/10/06 17:11:54 request_id=82f5f753-6324-4e02-81db-8d280db1a62d method=POST path=/api/v1/chats/:chat_id/messages status=201 response_bytes=219 latency=94.127µs
2026/10/06 17:11:54 request_id=6f6b00b8-cb66-4717-8807-45be0c9624a6 method=POST path=/api/v1/chats/:chat_id/messages status=201 response_bytes=219 latency=98.002µs
2026/10/06 17:11:54 request_id=2830cee7-de53-4cd0-849f-d292ac297908 method=POST path=/api/v1/chats/:chat_id/messages status=201 response_bytes=219 latency=85.627µs
2026/10/06 17:11:54 request_id=30afc48b-823d-400f-8683-01aafdb2f0cc method=POST path=/api/v1/chats/:chat_id/messages status=201 response_bytes=219 latency=83.044µs
2026/10/06 17:11:54 request_id=a3a47618-ef31-4e62-9dd7-157aa4660b7e method=POST path=/api/v1/chats/:chat_id/messages status=201 response_bytes=219 latency=153.962µs
2026/10/06 17:11:54 request_id=95fd0d00-462a-408e-8ed6-47b775feafd2 method=POST path=/api/v1/chats/:chat_id/messages status=201 response_bytes=219 latency=242.839µs
2026/10/06 17:11:54 request_id=4f4d182b-f220-4679-990f-2f5700ae38b3 method=POST path=/api/v1/chats/:chat_id/messages status=201 response_bytes=219 latency=81.918µs
2026/10/06 17:11:54 request_id=957a46c2-34d9-4c3d-9e07-22e426203752 method=POST path=/api/v1/chats/:chat_id/messages status=201 response_bytes=219 latency=94.793µs
2026/10/06 17:11:54 request_id=3ba94dd6-4790-470e-b154-82568881bf71 method=POST path=/api/v1/chats/:chat_id/messages status=201 response_bytes=219 latency=79.877µs
2026/10/06 17:11:54 request_id=e15e462b-0365-47e0-bf2b-70a6dba91071 method=POST path=/api/v1/chats/:chat_id/messages status=201 response_bytes=219 latency=79.919µs
2026/10/06 17:11:54 request_id=f9bf4a10-59a1-4c97-bb5c-6675c489efe6 method=POST path=/api/v1/chats/:chat_id/messages status=201 response_bytes=219 latency=85.044µs
2026/10/06 17:11:54 request_id=9f32f216-9b6c-4e31-9a66-0c093841c7cd method=POST path=/api/v1/chats/:chat_id/messages status=201 response_bytes=219 latency=207.963µs
2026/10/06 17:11:54 request_id=6d011e35-67c4-472c-b016-a96856287c97 method=POST path=/api/v1/chats/:chat_id/messages status=201 response_bytes=219 latency=155.587µs
2026/10/06 17:11:54 request_id=d3cb8aec-2279-4e29-83e5-df900e3c38aa method=POST path=/api/v1/chats/:chat_id/messages status=201 response_bytes=219 latency=91.336µs
2026/10/06 17:11:54 request_id=ec0e1ceb-9320-48a9-b07f-559023446992 method=POST path=/api/v1/chats/:chat_id/messages status=201 response_bytes=219 latency=92.877µs
2026/10/06 17:11:54 request_id=a702a45e-6259-4a4b-ac8d-f58e18584678 method=GET path=/api/v1/chats/:chat_id/messages status=200 response_bytes=3992 latency=624.723µs
2026/10/06 17:11:54 request_id=d225891a-5a65-4fe9-8220-7c33910ec911 method=GET path=/api/v1/chats/:chat_id/messages status=200 response_bytes=3992 latency=682.683µs
2026/10/06 17:11:54 request_id=74c04fdb-a93e-4694-8ed9-d6ed5b0fe9db method=GET path=/api/v1/chats/:chat_id/messages status=200 response_bytes=3992 latency=674.683µs
2026/10/06 17:11:54 request_id=7781b280-fcbf-4444-a150-08ee0428d7ca method=GET path=/api/v1/chats/:chat_id/messages status=200 response_bytes=3992 latency=625.806µs
2026/10/06 17:11:54 request_id=09eb9746-8eb9-4fb4-99cb-28f0c44837d7 method=GET path=/api/v1/chats/:chat_id/messages status=200 response_bytes=3992 latency=496.637µs
2026/10/06 17:11:54 request_id=1030f7c9-a007-4fbb-bb3d-b72710684290 method=GET path=/api/v1/chats/:chat_id/messages status=200 response_bytes=3316 latency=387.759µs
--- PASS: TestConcurrentMessagesAreUnique (5.52s)
PASS
ok gitflic.ru/akselbant/mtusi2026lab1-fork/internal/app/chat 9.600s
? gitflic.ru/akselbant/mtusi2026lab1-fork/internal/config [no test files]
? gitflic.ru/akselbant/mtusi2026lab1-fork/internal/pkg/domain [no test files]
=== RUN TestUnicodeAndSalt
--- PASS: TestUnicodeAndSalt (1.85s)
PASS
ok gitflic.ru/akselbant/mtusi2026lab1-fork/internal/pkg/password 2.888s
? gitflic.ru/akselbant/mtusi2026lab1-fork/internal/pkg/repository [no test files]
=== RUN TestIntegration
=== RUN TestIntegration/registration_race
storage_test.go:98: 12 concurrent INSERTs: 1 success, 11 unique conflicts
=== RUN TestIntegration/rollback
storage_test.go:116: failed second member INSERT left 0 chats and 0 members
=== RUN TestIntegration/keyset_and_explain
storage_test.go:163: EXPLAIN on 10,000 messages, cursor near the end (9,000):
storage_test.go:169: Limit (cost=0.29..16.15 rows=51 width=142) (actual time=0.010..0.023 rows=51 loops=1)
storage_test.go:169: Buffers: shared hit=5
storage_test.go:169: -> Index Scan using messages_history_idx on messages m (cost=0.29..311.35 rows=1000 width=142) (actual time=0.009..0.020 rows=51 loops=1)
storage_test.go:169: Index Cond: ((chat_id = 'cc3f7b83-6110-4ef9-91a7-948c2195b290'::uuid) AND (ROW(created_at, id) > ROW('2026-01-01 00:00:00.9+00'::timestamp with time zone, '00000000-0000-0000-0000-000000000000'::uuid)))
storage_test.go:169: Buffers: shared hit=5
storage_test.go:169: Planning Time: 0.029 ms
storage_test.go:169: Execution Time: 0.035 ms
storage_test.go:174: keyset traversal returned 10,000 distinct messages, including equal timestamps
--- PASS: TestIntegration (0.31s)
--- PASS: TestIntegration/registration_race (0.03s)
--- PASS: TestIntegration/rollback (0.00s)
--- PASS: TestIntegration/keyset_and_explain (0.06s)
PASS
ok gitflic.ru/akselbant/mtusi2026lab1-fork/internal/pkg/repository/postgres 1.314s
? gitflic.ru/akselbant/mtusi2026lab1-fork/internal/pkg/session [no test files]
? gitflic.ru/akselbant/mtusi2026lab1-fork/internal/usecase/chat [no test files]
? gitflic.ru/akselbant/mtusi2026lab1-fork/migrations [no test files]
+17
View File
@@ -0,0 +1,17 @@
{
"lab": 2,
"workload": "closed-loop POST messages; no automatic retries",
"requested_duration_seconds": 30.0,
"elapsed_seconds": 30.016,
"concurrency": 4,
"successful_requests": 25398,
"failed_requests": 0,
"error_ratio": 0.0,
"successful_rps": 846.152,
"successful_latency_ms": {
"p50": 4.419,
"p95": 6.588,
"p99": 10.795
},
"note": "Latency percentiles cover successes only. Timeouts/errors are counted separately; closed-loop has coordinated omission and client overhead."
}
+15
View File
@@ -0,0 +1,15 @@
./scripts/compose.sh run --rm migrations status
Container mtusi2026lab2-postgres-1 Running
Container mtusi2026lab2-postgres-1 Waiting
Container mtusi2026lab2-postgres-1 Healthy
Container mtusi2026lab2-migrations-run-d318a765b8c2 Creating
Container mtusi2026lab2-migrations-run-d318a765b8c2 Created
2026/10/06 19:20:08 Applied At Migration
2026/10/06 19:20:08 =======================================
2026/10/06 19:20:08 Tue Oct 6 19:19:45 2026 -- 001_initial.sql
Container mtusi2026lab2-postgres-1 Running
Container mtusi2026lab2-postgres-1 Waiting
Container mtusi2026lab2-postgres-1 Healthy
Container mtusi2026lab2-migrations-run-e28c525e3fa6 Creating
Container mtusi2026lab2-migrations-run-e28c525e3fa6 Created
2026/10/06 19:20:09 goose: no migrations to run. current version: 1
+13
View File
@@ -0,0 +1,13 @@
Before full restart:
/mtusi2026lab2-api-1 started=2026-10-06T17:10:58.047419969Z image=mtusi-messenger:lab2
/mtusi2026lab2-postgres-1 started=2026-10-06T17:08:11.606394684Z image=postgres:17.6-alpine3.22
/mtusi2026lab2-redis-1 started=2026-10-06T17:08:23.717771608Z image=redis:7.4.5-alpine3.21
python3 tests/resilience.py --mode persistence --action-script "scripts/restart.sh" --base-url "http://localhost:8080"
Executing explicit persistence hook; hook output suppressed to avoid leaking secrets.
PASS: persistence preserved confirmed data and existing session. Hook scope needs operator evidence.
After full restart:
/mtusi2026lab2-api-1 started=2026-10-06T17:12:57.850873498Z image=mtusi-messenger:lab2
/mtusi2026lab2-postgres-1 started=2026-10-06T17:12:55.217411712Z image=postgres:17.6-alpine3.22
/mtusi2026lab2-redis-1 started=2026-10-06T17:12:55.216978118Z image=redis:7.4.5-alpine3.21
+395
View File
@@ -0,0 +1,395 @@
{
"warmup_seconds": 3,
"dataset_before": {
"users": 25,
"chats": 6,
"messages": 2471
},
"dataset_after": {
"users": 28,
"chats": 7,
"messages": 27869
},
"samples": [
{
"elapsed_sample": 0,
"containers": [
{
"BlockIO": "0B / 0B",
"CPUPerc": "32.14%",
"Container": "a48895e0f6d1a0927a7f86f66eb96b10da08f9e23325419bcc2a8b5aaf3f3d16",
"ID": "a48895e0f6d1",
"MemPerc": "3.69%",
"MemUsage": "9.441MiB / 256MiB",
"Name": "mtusi2026lab2-api-1",
"NetIO": "8.29MB / 7.53MB",
"PIDs": "9"
},
{
"BlockIO": "1.02MB / 19.4MB",
"CPUPerc": "23.57%",
"Container": "77213fc2e88768555644a9ad27eddbf8359d1acd6972fe98939d435c2f37eefd",
"ID": "77213fc2e887",
"MemPerc": "5.89%",
"MemUsage": "30.17MiB / 512MiB",
"Name": "mtusi2026lab2-postgres-1",
"NetIO": "3.15MB / 3.87MB",
"PIDs": "10"
},
{
"BlockIO": "0B / 0B",
"CPUPerc": "2.47%",
"Container": "364ece262ab0328d7a8d357c014853c28eae478d00f82755105b4961bf56823e",
"ID": "364ece262ab0",
"MemPerc": "2.64%",
"MemUsage": "3.379MiB / 128MiB",
"Name": "mtusi2026lab2-redis-1",
"NetIO": "635kB / 669kB",
"PIDs": "6"
}
]
},
{
"elapsed_sample": 1,
"containers": [
{
"BlockIO": "98.3kB / 0B",
"CPUPerc": "28.50%",
"Container": "a48895e0f6d1a0927a7f86f66eb96b10da08f9e23325419bcc2a8b5aaf3f3d16",
"ID": "a48895e0f6d1",
"MemPerc": "3.94%",
"MemUsage": "10.1MiB / 256MiB",
"Name": "mtusi2026lab2-api-1",
"NetIO": "13.8MB / 12.5MB",
"PIDs": "9"
},
{
"BlockIO": "1.02MB / 36.6MB",
"CPUPerc": "29.65%",
"Container": "77213fc2e88768555644a9ad27eddbf8359d1acd6972fe98939d435c2f37eefd",
"ID": "77213fc2e887",
"MemPerc": "6.40%",
"MemUsage": "32.76MiB / 512MiB",
"Name": "mtusi2026lab2-postgres-1",
"NetIO": "5.8MB / 7.13MB",
"PIDs": "11"
},
{
"BlockIO": "0B / 0B",
"CPUPerc": "3.38%",
"Container": "364ece262ab0328d7a8d357c014853c28eae478d00f82755105b4961bf56823e",
"ID": "364ece262ab0",
"MemPerc": "2.65%",
"MemUsage": "3.387MiB / 128MiB",
"Name": "mtusi2026lab2-redis-1",
"NetIO": "1.05MB / 1.11MB",
"PIDs": "6"
}
]
},
{
"elapsed_sample": 2,
"containers": [
{
"BlockIO": "98.3kB / 0B",
"CPUPerc": "29.97%",
"Container": "a48895e0f6d1a0927a7f86f66eb96b10da08f9e23325419bcc2a8b5aaf3f3d16",
"ID": "a48895e0f6d1",
"MemPerc": "3.94%",
"MemUsage": "10.1MiB / 256MiB",
"Name": "mtusi2026lab2-api-1",
"NetIO": "19.5MB / 17.7MB",
"PIDs": "9"
},
{
"BlockIO": "1.02MB / 53.8MB",
"CPUPerc": "32.22%",
"Container": "77213fc2e88768555644a9ad27eddbf8359d1acd6972fe98939d435c2f37eefd",
"ID": "77213fc2e887",
"MemPerc": "6.56%",
"MemUsage": "33.59MiB / 512MiB",
"Name": "mtusi2026lab2-postgres-1",
"NetIO": "8.51MB / 10.5MB",
"PIDs": "11"
},
{
"BlockIO": "0B / 0B",
"CPUPerc": "2.50%",
"Container": "364ece262ab0328d7a8d357c014853c28eae478d00f82755105b4961bf56823e",
"ID": "364ece262ab0",
"MemPerc": "2.65%",
"MemUsage": "3.387MiB / 128MiB",
"Name": "mtusi2026lab2-redis-1",
"NetIO": "1.49MB / 1.57MB",
"PIDs": "6"
}
]
},
{
"elapsed_sample": 3,
"containers": [
{
"BlockIO": "500kB / 0B",
"CPUPerc": "28.98%",
"Container": "a48895e0f6d1a0927a7f86f66eb96b10da08f9e23325419bcc2a8b5aaf3f3d16",
"ID": "a48895e0f6d1",
"MemPerc": "4.11%",
"MemUsage": "10.52MiB / 256MiB",
"Name": "mtusi2026lab2-api-1",
"NetIO": "25.1MB / 22.8MB",
"PIDs": "9"
},
{
"BlockIO": "1.02MB / 77.3MB",
"CPUPerc": "32.34%",
"Container": "77213fc2e88768555644a9ad27eddbf8359d1acd6972fe98939d435c2f37eefd",
"ID": "77213fc2e887",
"MemPerc": "6.78%",
"MemUsage": "34.71MiB / 512MiB",
"Name": "mtusi2026lab2-postgres-1",
"NetIO": "12.2MB / 15MB",
"PIDs": "11"
},
{
"BlockIO": "0B / 0B",
"CPUPerc": "2.61%",
"Container": "364ece262ab0328d7a8d357c014853c28eae478d00f82755105b4961bf56823e",
"ID": "364ece262ab0",
"MemPerc": "2.65%",
"MemUsage": "3.387MiB / 128MiB",
"Name": "mtusi2026lab2-redis-1",
"NetIO": "1.77MB / 1.87MB",
"PIDs": "6"
}
]
},
{
"elapsed_sample": 4,
"containers": [
{
"BlockIO": "500kB / 0B",
"CPUPerc": "29.96%",
"Container": "a48895e0f6d1a0927a7f86f66eb96b10da08f9e23325419bcc2a8b5aaf3f3d16",
"ID": "a48895e0f6d1",
"MemPerc": "4.11%",
"MemUsage": "10.52MiB / 256MiB",
"Name": "mtusi2026lab2-api-1",
"NetIO": "28.9MB / 26.2MB",
"PIDs": "9"
},
{
"BlockIO": "1.02MB / 94.8MB",
"CPUPerc": "33.06%",
"Container": "77213fc2e88768555644a9ad27eddbf8359d1acd6972fe98939d435c2f37eefd",
"ID": "77213fc2e887",
"MemPerc": "6.99%",
"MemUsage": "35.79MiB / 512MiB",
"Name": "mtusi2026lab2-postgres-1",
"NetIO": "14.8MB / 18.2MB",
"PIDs": "11"
},
{
"BlockIO": "0B / 0B",
"CPUPerc": "2.57%",
"Container": "364ece262ab0328d7a8d357c014853c28eae478d00f82755105b4961bf56823e",
"ID": "364ece262ab0",
"MemPerc": "2.64%",
"MemUsage": "3.383MiB / 128MiB",
"Name": "mtusi2026lab2-redis-1",
"NetIO": "2.33MB / 2.46MB",
"PIDs": "6"
}
]
},
{
"elapsed_sample": 5,
"containers": [
{
"BlockIO": "500kB / 0B",
"CPUPerc": "29.54%",
"Container": "a48895e0f6d1a0927a7f86f66eb96b10da08f9e23325419bcc2a8b5aaf3f3d16",
"ID": "a48895e0f6d1",
"MemPerc": "4.11%",
"MemUsage": "10.52MiB / 256MiB",
"Name": "mtusi2026lab2-api-1",
"NetIO": "35.9MB / 32.6MB",
"PIDs": "9"
},
{
"BlockIO": "1.02MB / 106MB",
"CPUPerc": "31.21%",
"Container": "77213fc2e88768555644a9ad27eddbf8359d1acd6972fe98939d435c2f37eefd",
"ID": "77213fc2e887",
"MemPerc": "7.06%",
"MemUsage": "36.17MiB / 512MiB",
"Name": "mtusi2026lab2-postgres-1",
"NetIO": "16.5MB / 20.3MB",
"PIDs": "11"
},
{
"BlockIO": "0B / 0B",
"CPUPerc": "3.48%",
"Container": "364ece262ab0328d7a8d357c014853c28eae478d00f82755105b4961bf56823e",
"ID": "364ece262ab0",
"MemPerc": "2.64%",
"MemUsage": "3.383MiB / 128MiB",
"Name": "mtusi2026lab2-redis-1",
"NetIO": "2.73MB / 2.89MB",
"PIDs": "6"
}
]
},
{
"elapsed_sample": 6,
"containers": [
{
"BlockIO": "500kB / 0B",
"CPUPerc": "30.77%",
"Container": "a48895e0f6d1a0927a7f86f66eb96b10da08f9e23325419bcc2a8b5aaf3f3d16",
"ID": "a48895e0f6d1",
"MemPerc": "4.11%",
"MemUsage": "10.52MiB / 256MiB",
"Name": "mtusi2026lab2-api-1",
"NetIO": "41MB / 37.3MB",
"PIDs": "9"
},
{
"BlockIO": "1.02MB / 127MB",
"CPUPerc": "32.01%",
"Container": "77213fc2e88768555644a9ad27eddbf8359d1acd6972fe98939d435c2f37eefd",
"ID": "77213fc2e887",
"MemPerc": "7.24%",
"MemUsage": "37.05MiB / 512MiB",
"Name": "mtusi2026lab2-postgres-1",
"NetIO": "19.8MB / 24.4MB",
"PIDs": "11"
},
{
"BlockIO": "0B / 0B",
"CPUPerc": "3.42%",
"Container": "364ece262ab0328d7a8d357c014853c28eae478d00f82755105b4961bf56823e",
"ID": "364ece262ab0",
"MemPerc": "2.64%",
"MemUsage": "3.383MiB / 128MiB",
"Name": "mtusi2026lab2-redis-1",
"NetIO": "2.99MB / 3.17MB",
"PIDs": "6"
}
]
},
{
"elapsed_sample": 7,
"containers": [
{
"BlockIO": "500kB / 0B",
"CPUPerc": "30.67%",
"Container": "a48895e0f6d1a0927a7f86f66eb96b10da08f9e23325419bcc2a8b5aaf3f3d16",
"ID": "a48895e0f6d1",
"MemPerc": "4.11%",
"MemUsage": "10.52MiB / 256MiB",
"Name": "mtusi2026lab2-api-1",
"NetIO": "44.4MB / 40.3MB",
"PIDs": "9"
},
{
"BlockIO": "1.02MB / 142MB",
"CPUPerc": "31.81%",
"Container": "77213fc2e88768555644a9ad27eddbf8359d1acd6972fe98939d435c2f37eefd",
"ID": "77213fc2e887",
"MemPerc": "7.39%",
"MemUsage": "37.85MiB / 512MiB",
"Name": "mtusi2026lab2-postgres-1",
"NetIO": "22.2MB / 27.3MB",
"PIDs": "11"
},
{
"BlockIO": "0B / 0B",
"CPUPerc": "3.47%",
"Container": "364ece262ab0328d7a8d357c014853c28eae478d00f82755105b4961bf56823e",
"ID": "364ece262ab0",
"MemPerc": "2.64%",
"MemUsage": "3.383MiB / 128MiB",
"Name": "mtusi2026lab2-redis-1",
"NetIO": "3.49MB / 3.7MB",
"PIDs": "6"
}
]
},
{
"elapsed_sample": 8,
"containers": [
{
"BlockIO": "500kB / 0B",
"CPUPerc": "29.70%",
"Container": "a48895e0f6d1a0927a7f86f66eb96b10da08f9e23325419bcc2a8b5aaf3f3d16",
"ID": "a48895e0f6d1",
"MemPerc": "4.11%",
"MemUsage": "10.52MiB / 256MiB",
"Name": "mtusi2026lab2-api-1",
"NetIO": "51.6MB / 46.8MB",
"PIDs": "9"
},
{
"BlockIO": "1.02MB / 159MB",
"CPUPerc": "31.18%",
"Container": "77213fc2e88768555644a9ad27eddbf8359d1acd6972fe98939d435c2f37eefd",
"ID": "77213fc2e887",
"MemPerc": "7.60%",
"MemUsage": "38.93MiB / 512MiB",
"Name": "mtusi2026lab2-postgres-1",
"NetIO": "24.9MB / 30.6MB",
"PIDs": "11"
},
{
"BlockIO": "0B / 0B",
"CPUPerc": "3.53%",
"Container": "364ece262ab0328d7a8d357c014853c28eae478d00f82755105b4961bf56823e",
"ID": "364ece262ab0",
"MemPerc": "2.64%",
"MemUsage": "3.383MiB / 128MiB",
"Name": "mtusi2026lab2-redis-1",
"NetIO": "3.78MB / 4MB",
"PIDs": "6"
}
]
},
{
"elapsed_sample": 9,
"containers": [
{
"BlockIO": "631kB / 0B",
"CPUPerc": "28.30%",
"Container": "a48895e0f6d1a0927a7f86f66eb96b10da08f9e23325419bcc2a8b5aaf3f3d16",
"ID": "a48895e0f6d1",
"MemPerc": "4.16%",
"MemUsage": "10.65MiB / 256MiB",
"Name": "mtusi2026lab2-api-1",
"NetIO": "57.1MB / 51.8MB",
"PIDs": "9"
},
{
"BlockIO": "1.02MB / 176MB",
"CPUPerc": "30.96%",
"Container": "77213fc2e88768555644a9ad27eddbf8359d1acd6972fe98939d435c2f37eefd",
"ID": "77213fc2e887",
"MemPerc": "7.73%",
"MemUsage": "39.58MiB / 512MiB",
"Name": "mtusi2026lab2-postgres-1",
"NetIO": "27.6MB / 33.9MB",
"PIDs": "11"
},
{
"BlockIO": "0B / 0B",
"CPUPerc": "2.57%",
"Container": "364ece262ab0328d7a8d357c014853c28eae478d00f82755105b4961bf56823e",
"ID": "364ece262ab0",
"MemPerc": "2.64%",
"MemUsage": "3.383MiB / 128MiB",
"Name": "mtusi2026lab2-redis-1",
"NetIO": "4.2MB / 4.45MB",
"PIDs": "6"
}
]
}
]
}
+2
View File
@@ -0,0 +1,2 @@
python3 tests/smoke.py --base-url "http://localhost:8080"
PASS: lab2 public API scenario; infrastructure and grading evidence remain separate.
+4
View File
@@ -0,0 +1,4 @@
/tmp/mtusi-lab2-validation/bin/python scripts/validate_openapi.py
/private/tmp/mtusi-lab2-validation/lib/python3.9/site-packages/urllib3/__init__.py:35: NotOpenSSLWarning: urllib3 v2 only supports OpenSSL 1.1.1+, currently the 'ssl' module is compiled with 'LibreSSL 2.8.3'. See: https://github.com/urllib3/urllib3/issues/3020
warnings.warn(
PASS: full OpenAPI 3.1 and JSON Schema validation; application NOT tested.
+31
View File
@@ -0,0 +1,31 @@
module gitflic.ru/akselbant/mtusi2026lab1-fork
go 1.26.4
require (
github.com/google/uuid v1.6.0
github.com/jackc/pgx/v5 v5.7.6
github.com/labstack/echo/v4 v4.13.4
github.com/redis/go-redis/v9 v9.12.1
github.com/swaggest/swgui v1.8.9
golang.org/x/crypto v0.38.0
)
require (
github.com/cespare/xxhash/v2 v2.3.0 // indirect
github.com/dgryski/go-rendezvous v0.0.0-20200823014737-9f7001d12a5f // indirect
github.com/jackc/pgpassfile v1.0.0 // indirect
github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761 // indirect
github.com/jackc/puddle/v2 v2.2.2 // indirect
github.com/labstack/gommon v0.4.2 // indirect
github.com/mattn/go-colorable v0.1.14 // indirect
github.com/mattn/go-isatty v0.0.20 // indirect
github.com/valyala/bytebufferpool v1.0.0 // indirect
github.com/valyala/fasttemplate v1.2.2 // indirect
github.com/vearutop/statigz v1.4.0 // indirect
golang.org/x/net v0.40.0 // indirect
golang.org/x/sync v0.14.0 // indirect
golang.org/x/sys v0.33.0 // indirect
golang.org/x/text v0.25.0 // indirect
golang.org/x/time v0.11.0 // indirect
)
+67
View File
@@ -0,0 +1,67 @@
github.com/andybalholm/brotli v1.0.5 h1:8uQZIdzKmjc/iuPu7O2ioW48L81FgatrcpfFmiq/cCs=
github.com/andybalholm/brotli v1.0.5/go.mod h1:fO7iG3H7G2nSZ7m0zPUDn85XEX2GTukHGRSepvi9Eig=
github.com/bool64/dev v0.2.45 h1:3nLKhAS/6Oklk3Mt2lHYSN/Cb4tdAD77KLwzeP+6eYE=
github.com/bool64/dev v0.2.45/go.mod h1:iJbh1y/HkunEPhgebWRNcs8wfGq7sjvJ6W5iabL8ACg=
github.com/bsm/ginkgo/v2 v2.12.0 h1:Ny8MWAHyOepLGlLKYmXG4IEkioBysk6GpaRTLC8zwWs=
github.com/bsm/ginkgo/v2 v2.12.0/go.mod h1:SwYbGRRDovPVboqFv0tPTcG1sN61LM1Z4ARdbAV9g4c=
github.com/bsm/gomega v1.27.10 h1:yeMWxP2pV2fG3FgAODIY8EiRE3dy0aeFYt4l7wh6yKA=
github.com/bsm/gomega v1.27.10/go.mod h1:JyEr/xRbxbtgWNi8tIEVPUYZ5Dzef52k01W3YH0H+O0=
github.com/cespare/xxhash/v2 v2.3.0 h1:UL815xU9SqsFlibzuggzjXhog7bL6oX9BbNZnL2UFvs=
github.com/cespare/xxhash/v2 v2.3.0/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs=
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/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/dgryski/go-rendezvous v0.0.0-20200823014737-9f7001d12a5f h1:lO4WD4F/rVNCu3HqELle0jiPLLBs70cWOduZpkS1E78=
github.com/dgryski/go-rendezvous v0.0.0-20200823014737-9f7001d12a5f/go.mod h1:cuUVRXasLTGF7a8hSLbxyZXjz+1KgoB3wDUb6vlszIc=
github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0=
github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
github.com/jackc/pgpassfile v1.0.0 h1:/6Hmqy13Ss2zCq62VdNG8tM1wchn8zjSGOBJ6icpsIM=
github.com/jackc/pgpassfile v1.0.0/go.mod h1:CEx0iS5ambNFdcRtxPj5JhEz+xB6uRky5eyVu/W2HEg=
github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761 h1:iCEnooe7UlwOQYpKFhBabPMi4aNAfoODPEFNiAnClxo=
github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761/go.mod h1:5TJZWKEWniPve33vlWYSoGYefn3gLQRzjfDlhSJ9ZKM=
github.com/jackc/pgx/v5 v5.7.6 h1:rWQc5FwZSPX58r1OQmkuaNicxdmExaEz5A2DO2hUuTk=
github.com/jackc/pgx/v5 v5.7.6/go.mod h1:aruU7o91Tc2q2cFp5h4uP3f6ztExVpyVv88Xl/8Vl8M=
github.com/jackc/puddle/v2 v2.2.2 h1:PR8nw+E/1w0GLuRFSmiioY6UooMp6KJv0/61nB7icHo=
github.com/jackc/puddle/v2 v2.2.2/go.mod h1:vriiEXHvEE654aYKXXjOvZM39qJ0q+azkZFrfEOc3H4=
github.com/labstack/echo/v4 v4.13.4 h1:oTZZW+T3s9gAu5L8vmzihV7/lkXGZuITzTQkTEhcXEA=
github.com/labstack/echo/v4 v4.13.4/go.mod h1:g63b33BZ5vZzcIUF8AtRH40DrTlXnx4UMC8rBdndmjQ=
github.com/labstack/gommon v0.4.2 h1:F8qTUNXgG1+6WQmqoUWnz8WiEU60mXVVw0P4ht1WRA0=
github.com/labstack/gommon v0.4.2/go.mod h1:QlUFxVM+SNXhDL/Z7YhocGIBYOiwB0mXm1+1bAPHPyU=
github.com/mattn/go-colorable v0.1.14 h1:9A9LHSqF/7dyVVX6g0U9cwm9pG3kP9gSzcuIPHPsaIE=
github.com/mattn/go-colorable v0.1.14/go.mod h1:6LmQG8QLFO4G5z1gPvYEzlUgJ2wF+stgPZH1UqBm1s8=
github.com/mattn/go-isatty v0.0.20 h1:xfD0iDuEKnDkl03q4limB+vH+GxLEtL/jb4xVJSWWEY=
github.com/mattn/go-isatty v0.0.20/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y=
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.12.1 h1:k5iquqv27aBtnTm2tIkROUDp8JBXhXZIVu1InSgvovg=
github.com/redis/go-redis/v9 v9.12.1/go.mod h1:huWgSWd8mW6+m0VPhJjSSQ+d6Nh1VICQ6Q5lHuCH/Iw=
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI=
github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
github.com/stretchr/testify v1.10.0 h1:Xv5erBjTwe/5IxqUQTdXv5kgmIvbHo3QQyRwhJsOfJA=
github.com/stretchr/testify v1.10.0/go.mod h1:r2ic/lqez/lEtzL7wO/rwa5dbSLXVDPFyf8C91i36aY=
github.com/swaggest/swgui v1.8.9 h1:cxAgIwouPpZPlvX68jY5fpwarzLbkc8/IL6DMj+H460=
github.com/swaggest/swgui v1.8.9/go.mod h1:eTJfgwudbyw9xMwqO26vs82ei2u6//JnUAofx2vGB3M=
github.com/valyala/bytebufferpool v1.0.0 h1:GqA5TC/0021Y/b9FG4Oi9Mr3q7XYx6KllzawFIhcdPw=
github.com/valyala/bytebufferpool v1.0.0/go.mod h1:6bBcMArwyJ5K/AmCkWv1jt77kVWyCJ6HpOuEn7z0Csc=
github.com/valyala/fasttemplate v1.2.2 h1:lxLXG0uE3Qnshl9QyaK6XJxMXlQZELvChBOCmQD0Loo=
github.com/valyala/fasttemplate v1.2.2/go.mod h1:KHLXt3tVN2HBp8eijSv/kGJopbvo7S+qRAEEKiv+SiQ=
github.com/vearutop/statigz v1.4.0 h1:RQL0KG3j/uyA/PFpHeZ/L6l2ta920/MxlOAIGEOuwmU=
github.com/vearutop/statigz v1.4.0/go.mod h1:LYTolBLiz9oJISwiVKnOQoIwhO1LWX1A7OECawGS8XE=
golang.org/x/crypto v0.38.0 h1:jt+WWG8IZlBnVbomuhg2Mdq0+BBQaHbtqHEFEigjUV8=
golang.org/x/crypto v0.38.0/go.mod h1:MvrbAqul58NNYPKnOra203SB9vpuZW0e+RRZV+Ggqjw=
golang.org/x/net v0.40.0 h1:79Xs7wF06Gbdcg4kdCCIQArK11Z1hr5POQ6+fIYHNuY=
golang.org/x/net v0.40.0/go.mod h1:y0hY0exeL2Pku80/zKK7tpntoX23cqL3Oa6njdgRtds=
golang.org/x/sync v0.14.0 h1:woo0S4Yywslg6hp4eUFjTVOyKt0RookbpAHG4c1HmhQ=
golang.org/x/sync v0.14.0/go.mod h1:1dzgHSNfp02xaA81J2MS99Qcpr2w7fw1gpm99rleRqA=
golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.33.0 h1:q3i8TbbEz+JRD9ywIRlyRAQbM0qF7hu24q3teo2hbuw=
golang.org/x/sys v0.33.0/go.mod h1:BJP2sWEmIv4KK5OTEluFJCKSidICx8ciO85XgH3Ak8k=
golang.org/x/text v0.25.0 h1:qVyWApTSYLk/drJRO5mDlNYskwQznZmkpV2c8q9zls4=
golang.org/x/text v0.25.0/go.mod h1:WEdwpYrmk1qmdHvhkSTNPm3app7v4rsT8F2UD6+VHIA=
golang.org/x/time v0.11.0 h1:/bpjEDfN9tkoN/ryeYHnv5hcMlc8ncjMcM4XBk5NWV0=
golang.org/x/time v0.11.0/go.mod h1:CDIdPxbZBQxdj6cxyCIdrNogrJKMJ7pr37NYpMcMDSg=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
+56 -4
View File
@@ -1,7 +1,59 @@
# Инфраструктура студента
# Локальный стенд lab2
Здесь разместите конфигурации выбранных сервисов; основную топологию — в корневом compose.yaml/stack.yaml. `compose.example.yaml` — только worksheet ролей и намеренно не запускается. `contracts/infrastructure.json` задаёт минимальные роли, не готовые образы/пароли.
`make up` создаёт локальные секреты и запускает `compose.yaml`: API, PostgreSQL 17.6,
Redis 7.4.5. Единственный опубликованный порт — API на `127.0.0.1:8080`.
Порт 8080 используется по умолчанию, параметр PORT можно не передавать.
В REPORT.md сопоставьте роль → service name → версия/digest → health/readiness → volume → сеть/порт → способ передачи credentials. Приведите bootstrap (schema, bucket, broker topology, а с lab6 provisioning) и безопасное повторение этих команд.
`./scripts/compose.sh` выбирает Docker Compose plugin либо standalone docker-compose;
он использует `--env-file /dev/null`. Настройки задаются Compose-манифестом и переменными
процесса, автоматическое чтение локальных env-файлов не требуется.
Приложение строится из исходников. Не используйте заранее существующий образ преподавательского сервера вместо своей реализации. Restart hook перезапускает все соответствующие stores с volumes; failover hook останавливает только заданную API-реплику.
`make bootstrap` генерирует `secrets/postgres_password` и `secrets/cursor_key` только
при отсутствии содержимого. Файлы не печатаются и исключены из Git и Docker context.
Каталог имеет права 0700, файлы 0444 для чтения непривилегированным API через Compose
secrets на Linux. Не меняйте пароль PostgreSQL при существующем volume без ALTER ROLE.
Не меняйте cursor_key, если нужно сохранить действительность выданных cursor.
## Настройки API
| Переменная | По умолчанию | Назначение |
| --- | --- | --- |
| PORT | 8080 | Порт процесса; в Compose внешний PORT перенаправляется на внутренний 8080 |
| POSTGRES_HOST / POSTGRES_PORT | localhost / 5432 | Адрес PostgreSQL; в Compose host=postgres |
| POSTGRES_USER / POSTGRES_DB | messenger / messenger | Роль и БД |
| POSTGRES_PASSWORD_FILE | обязателен файл или POSTGRES_PASSWORD | Пароль, созданный bootstrap |
| POSTGRES_MAX_CONNS | 10 | Верхняя граница pgxpool (min=1, idle=5m, lifetime=1h) |
| REDIS_ADDR | localhost:6379 | В Compose redis:6379 |
| QUERY_TIMEOUT_MS | 2000 | Таймаут SQL, соединения, Redis, ожидания пула |
| SESSION_TTL_SECONDS | 3600 | Абсолютный срок сессии; для проверки expiry 2 |
| CURSOR_KEY_FILE | обязателен файл или CURSOR_KEY | 32 случайных байта в hex для HMAC cursor |
Миграции применяет **goose CLI v3.27.1** в отдельном сервисе `migrations`.
Compose запускает API только после успешного `goose up`. В бинарнике API нет
кода миграций. SQL-файлы содержат `-- +goose Up` и `-- +goose Down`;
версия хранится в `goose_db_version`, DDL и версия коммитятся одной транзакцией.
Миграции выполняет один сервис, параллельные ручные запуски не предполагаются.
Схема описана в [schema.md](schema.md).
- `make migrate` — собрать утилиту и выполнить `goose up`.
- `make migrate-status` — показать применённые версии.
- `make migrate-down` — откатить последнюю миграцию. Для начальной миграции
это удаление всех таблиц приложения и данных; используйте только намеренно.
- Проверка SQL без БД: `goose -env /dev/null -dir migrations validate`.
Контейнер получает пароль через POSTGRES_PASSWORD_FILE и передаёт его драйверу
через PGPASSWORD, без пароля в argv. `-env /dev/null` отключает автоматическую
загрузку dotenv. Для локального goose задайте GOOSE_DRIVER=postgres и GOOSE_DBSTRING
с адресом/пользователем/БД, затем используйте тот же `-dir migrations`.
При переходе с прежнего runner миграция 001 распознаёт `schema_migrations` с
записью `001_initial.sql` и наличием четырёх таблиц приложения. Goose фиксирует
версию 1 без повторного DDL; данные сохраняются. Старый журнал остаётся только
для совместимости и больше не используется для новых версий. Отсутствующая
часть старой схемы приводит к ошибке, а не к молчаливому пропуску миграции.
PostgreSQL и Redis имеют отдельные именованные volumes. `make down` сохраняет их.
`scripts/restart.sh` останавливает и запускает API, PostgreSQL и Redis, не удаляя volumes.
Redis: TTL через SET PXAT, appendonly=yes, appendfsync=always, без eviction.
При исчерпании памяти запись сессии отклоняется с 503 вместо удаления действующих сессий.
Ready проверяет обе зависимости, live — только HTTP-процесс.
+8
View File
@@ -0,0 +1,8 @@
#!/bin/sh
set -eu
# Keep the password out of argv and disable automatic dotenv loading.
if [ -n "${POSTGRES_PASSWORD_FILE:-}" ]; then
PGPASSWORD=$(cat "$POSTGRES_PASSWORD_FILE")
export PGPASSWORD
fi
exec goose -env /dev/null -dir /migrations -timeout 30s "$@"
+9
View File
@@ -0,0 +1,9 @@
bind 0.0.0.0
protected-mode no
port 6379
dir /data
appendonly yes
appendfsync always
save ""
maxmemory 64mb
maxmemory-policy noeviction
+25
View File
@@ -0,0 +1,25 @@
# Схема и транзакционные границы
PostgreSQL — источник истины пользователей, чатов, участников и сообщений.
Redis — источник истины сессий: SHA-256 токена → user_id, expires_at; TTL до
абсолютного expires_at, без продления при чтении. Logout удаляет ключ.
Redis использует AOF с appendfsync always и отдельный именованный volume.
- users: UUID PK, UNIQUE(username), password_hash (Argon2id), display_name, created_at.
- chats: UUID PK, title, created_at; индекс (created_at, id).
- chat_members: PK(chat_id, user_id), FK к chats/users; ordinal сохраняет порядок
участников; UNIQUE(chat_id, ordinal); индекс (user_id, chat_id).
- messages: UUID PK, FK chat_id/sender_id через членство; text, created_at.
Индекс (chat_id, created_at, id) отвечает равенству по чату и keyset-предикату
(created_at, id) > ($timestamp, $id), ORDER BY created_at, id LIMIT $limit.
- goose_db_version: журнал goose CLI; SQL-миграция и запись её версии
коммитятся в одной транзакции. Сервис migrations завершается до старта API.
Регистрация — один INSERT, гонка разрешается UNIQUE, проигравшие получают 409.
Создание чата — одна транзакция: INSERT чата, затем участников; любой неверный
FK откатывает всю операцию, включая уже вставленных участников.
Отправка сообщения — один INSERT с FK на членство. Чтения идут в PostgreSQL,
кэша истории нет, подтверждённый COMMIT виден следующему запросу.
При конкурентной записи keyset не даёт snapshot: поздний COMMIT с ключом до
уже прочитанного cursor может быть пропущен. created_at задаёт PostgreSQL,
UUID разрешает совпадения времени; часы не используются как уникальный ID.
+31
View File
@@ -0,0 +1,31 @@
package chat
import (
"errors"
"github.com/labstack/echo/v4"
"gitflic.ru/akselbant/mtusi2026lab1-fork/internal/pkg/domain"
)
func (h *Chat) authorizedChat(c echo.Context, requestedChat domain.Chat) (domain.Chat, bool, error) {
chat, err := h.useCase.GetChat(c.Request().Context(), authenticatedUser(c).ID, requestedChat)
if err != nil {
return domain.Chat{}, false, h.useCaseError(c, err)
}
return chat, true, nil
}
func (h *Chat) cursorPosition(raw string, present bool, scope, owner string) (*domain.Position, error) {
if !present {
return nil, nil
}
if raw == "" {
return nil, errors.New("empty cursor")
}
createdAt, id, err := h.cursor.decode(raw, scope, owner)
if err != nil {
return nil, err
}
return &domain.Position{CreatedAt: createdAt, ID: id}, nil
}
+33
View File
@@ -0,0 +1,33 @@
package chat
import (
"net/http"
"github.com/labstack/echo/v4"
"gitflic.ru/akselbant/mtusi2026lab1-fork/dto"
"gitflic.ru/akselbant/mtusi2026lab1-fork/internal/pkg/domain"
)
func (h *Chat) createChat(c echo.Context) error {
var request dto.CreateChatRequest
if err := decodeJSON(c, &request); err != nil {
return h.jsonError(c, err)
}
callerID := authenticatedUser(c).ID
chat, err := h.useCase.CreateChat(c.Request().Context(), callerID, createChatRequestToDomain(request))
if err != nil {
return h.useCaseError(c, err)
}
return c.JSON(http.StatusCreated, createChatResponseFromDomain(chat))
}
func createChatRequestToDomain(request dto.CreateChatRequest) domain.Chat {
return domain.Chat{Title: request.Title, MemberIDs: request.MemberIDs}
}
func createChatResponseFromDomain(chat domain.Chat) dto.CreateChatResponse {
return dto.CreateChatResponse{
ID: chat.ID, Title: chat.Title, MemberIDs: chat.MemberIDs, CreatedAt: dto.Timestamp(chat.CreatedAt),
}
}
+42
View File
@@ -0,0 +1,42 @@
package chat
import (
"net/http"
"github.com/labstack/echo/v4"
"gitflic.ru/akselbant/mtusi2026lab1-fork/dto"
"gitflic.ru/akselbant/mtusi2026lab1-fork/internal/pkg/domain"
)
func (h *Chat) createMessage(c echo.Context) error {
request := dto.CreateMessageRequest{ChatID: c.Param("chat_id")}
chat, ok, err := h.authorizedChat(c, domain.Chat{ID: request.ChatID})
if err != nil {
return err
}
if !ok {
return nil
}
if err := decodeJSON(c, &request); err != nil {
return h.jsonError(c, err)
}
request.ChatID = chat.ID
message, err := h.useCase.CreateMessage(c.Request().Context(), authenticatedUser(c).ID, createMessageRequestToDomain(request))
if err != nil {
return h.useCaseError(c, err)
}
return c.JSON(http.StatusCreated, createMessageResponseFromDomain(message))
}
func createMessageRequestToDomain(request dto.CreateMessageRequest) domain.Message {
return domain.Message{ChatID: request.ChatID, Text: request.Text}
}
func createMessageResponseFromDomain(message domain.Message) dto.CreateMessageResponse {
return dto.CreateMessageResponse{
ID: message.ID, ChatID: message.ChatID, SenderID: message.SenderID,
Text: message.Text, CreatedAt: dto.Timestamp(message.CreatedAt),
}
}
+32
View File
@@ -0,0 +1,32 @@
package chat
import (
"net/http"
"github.com/labstack/echo/v4"
"gitflic.ru/akselbant/mtusi2026lab1-fork/dto"
"gitflic.ru/akselbant/mtusi2026lab1-fork/internal/pkg/domain"
)
func (h *Chat) createUser(c echo.Context) error {
var request dto.CreateUserRequest
if err := decodeJSON(c, &request); err != nil {
return h.jsonError(c, err)
}
user, err := h.useCase.CreateUser(c.Request().Context(), createUserRequestToDomain(request), request.Password)
if err != nil {
return h.useCaseError(c, err)
}
return c.JSON(http.StatusCreated, createUserResponseFromDomain(user))
}
func createUserRequestToDomain(request dto.CreateUserRequest) domain.User {
return domain.User{Username: request.Username, DisplayName: request.DisplayName}
}
func createUserResponseFromDomain(user domain.User) dto.CreateUserResponse {
return dto.CreateUserResponse{
ID: user.ID, Username: user.Username, DisplayName: user.DisplayName, CreatedAt: dto.Timestamp(user.CreatedAt),
}
}
+21
View File
@@ -0,0 +1,21 @@
package chat
import (
"net/http"
"github.com/labstack/echo/v4"
"gitflic.ru/akselbant/mtusi2026lab1-fork/dto"
"gitflic.ru/akselbant/mtusi2026lab1-fork/internal/pkg/domain"
)
func (h *Chat) currentUser(c echo.Context) error {
user := authenticatedUser(c)
return c.JSON(http.StatusOK, currentUserResponseFromDomain(user))
}
func currentUserResponseFromDomain(user domain.User) dto.CurrentUserResponse {
return dto.CurrentUserResponse{
ID: user.ID, Username: user.Username, DisplayName: user.DisplayName, CreatedAt: dto.Timestamp(user.CreatedAt),
}
}
+75
View File
@@ -0,0 +1,75 @@
package chat
import (
"crypto/hmac"
"crypto/sha256"
"encoding/base64"
"encoding/json"
"errors"
"strings"
"time"
"github.com/google/uuid"
)
type cursorPayload struct {
Scope string `json:"scope"`
Owner string `json:"owner"`
CreatedAt string `json:"created_at"`
ID string `json:"id"`
}
type cursorCodec struct {
secret [32]byte
}
func (c cursorCodec) encode(scope, owner string, createdAt time.Time, id string) string {
payload, err := json.Marshal(cursorPayload{
Scope: scope,
Owner: owner,
CreatedAt: createdAt.UTC().Format(time.RFC3339Nano),
ID: id,
})
if err != nil {
panic("cannot encode cursor: " + err.Error())
}
signature := c.sign(payload)
return base64.RawURLEncoding.EncodeToString(payload) + "." + base64.RawURLEncoding.EncodeToString(signature)
}
func (c cursorCodec) decode(raw, scope, owner string) (time.Time, string, error) {
parts := strings.Split(raw, ".")
if len(parts) != 2 {
return time.Time{}, "", errors.New("malformed cursor")
}
payload, err := base64.RawURLEncoding.DecodeString(parts[0])
if err != nil {
return time.Time{}, "", errors.New("malformed cursor")
}
signature, err := base64.RawURLEncoding.DecodeString(parts[1])
if err != nil || !hmac.Equal(signature, c.sign(payload)) {
return time.Time{}, "", errors.New("invalid cursor signature")
}
var value cursorPayload
if err := json.Unmarshal(payload, &value); err != nil {
return time.Time{}, "", errors.New("malformed cursor payload")
}
if value.Scope != scope || value.Owner != owner {
return time.Time{}, "", errors.New("cursor belongs to another resource")
}
parsedID, err := uuid.Parse(value.ID)
if err != nil || parsedID.String() != value.ID {
return time.Time{}, "", errors.New("malformed cursor id")
}
createdAt, err := time.Parse(time.RFC3339Nano, value.CreatedAt)
if err != nil {
return time.Time{}, "", errors.New("malformed cursor timestamp")
}
return createdAt, value.ID, nil
}
func (c cursorCodec) sign(payload []byte) []byte {
mac := hmac.New(sha256.New, c.secret[:])
_, _ = mac.Write(payload)
return mac.Sum(nil)
}
+91
View File
@@ -0,0 +1,91 @@
package chat
import (
"errors"
"net/http"
"github.com/google/uuid"
"github.com/labstack/echo/v4"
"gitflic.ru/akselbant/mtusi2026lab1-fork/dto"
"gitflic.ru/akselbant/mtusi2026lab1-fork/internal/pkg/domain"
)
func (h *Chat) invalid(c echo.Context, message string) error {
return h.writeError(c, http.StatusBadRequest, "invalid_request", message)
}
func (h *Chat) jsonError(c echo.Context, err error) error {
if errors.Is(err, errUnsupportedMediaType) {
return h.writeError(c, http.StatusUnsupportedMediaType, "unsupported_media_type", "Content-Type должен быть application/json")
}
var tooLarge *http.MaxBytesError
if errors.As(err, &tooLarge) {
return h.writeError(c, http.StatusRequestEntityTooLarge, "payload_too_large", "Тело запроса слишком большое")
}
return h.invalid(c, err.Error())
}
func (h *Chat) useCaseError(c echo.Context, err error) error {
applicationError, ok := domain.AsApplicationError(err)
if !ok {
return err
}
status := http.StatusInternalServerError
switch applicationError.Code {
case domain.ErrorUnavailable:
status = http.StatusServiceUnavailable
case domain.ErrorInvalid:
status = http.StatusBadRequest
case domain.ErrorUnauthorized:
status = http.StatusUnauthorized
challenge := `Bearer realm="messenger"`
if c.Path() == "/api/v1/auth/sessions" {
challenge = `Basic realm="messenger", charset="UTF-8"`
}
c.Response().Header().Set("WWW-Authenticate", challenge)
case domain.ErrorNotFound:
status = http.StatusNotFound
case domain.ErrorConflict:
status = http.StatusConflict
}
return h.writeError(c, status, string(applicationError.Code), applicationError.Message)
}
func (h *Chat) writeError(c echo.Context, status int, code, message string) error {
return c.JSON(status, dto.ErrorResponse{Error: dto.ErrorDetails{
Code: code,
Message: message,
RequestID: requestID(c),
}})
}
func (h *Chat) httpErrorHandler(err error, c echo.Context) {
if c.Response().Committed {
return
}
status := http.StatusInternalServerError
code := "internal_error"
message := "Внутренняя ошибка сервера"
var httpError *echo.HTTPError
if errors.As(err, &httpError) {
status = httpError.Code
switch status {
case http.StatusNotFound:
code, message = "not_found", "Объект не найден"
case http.StatusMethodNotAllowed, http.StatusBadRequest:
code, message = "invalid_request", "Некорректный запрос"
}
}
_ = h.writeError(c, status, code, message)
}
func requestID(c echo.Context) string {
value, _ := c.Get(requestIDKey).(string)
if value == "" {
value = uuid.NewString()
c.Set(requestIDKey, value)
c.Response().Header().Set("X-Request-Id", value)
}
return value
}
+32
View File
@@ -0,0 +1,32 @@
package chat
import (
"net/http"
"github.com/labstack/echo/v4"
"gitflic.ru/akselbant/mtusi2026lab1-fork/dto"
"gitflic.ru/akselbant/mtusi2026lab1-fork/internal/pkg/domain"
)
func (h *Chat) getChat(c echo.Context) error {
request := dto.GetChatRequest{ChatID: c.Param("chat_id")}
chat, ok, err := h.authorizedChat(c, getChatRequestToDomain(request))
if err != nil {
return err
}
if !ok {
return nil
}
return c.JSON(http.StatusOK, getChatResponseFromDomain(chat))
}
func getChatRequestToDomain(request dto.GetChatRequest) domain.Chat {
return domain.Chat{ID: request.ChatID}
}
func getChatResponseFromDomain(chat domain.Chat) dto.GetChatResponse {
return dto.GetChatResponse{
ID: chat.ID, Title: chat.Title, MemberIDs: chat.MemberIDs, CreatedAt: dto.Timestamp(chat.CreatedAt),
}
}
+53
View File
@@ -0,0 +1,53 @@
package chat
import (
"net/http"
"github.com/labstack/echo/v4"
"gitflic.ru/akselbant/mtusi2026lab1-fork/dto"
"gitflic.ru/akselbant/mtusi2026lab1-fork/internal/pkg/domain"
)
func (h *Chat) listChats(c echo.Context) error {
limit, err := parseLimit(c)
if err != nil {
return h.invalid(c, err.Error())
}
rawCursor, cursorPresent, err := oneQueryValue(c, "cursor")
if err != nil {
return h.invalid(c, "cursor должен быть указан один раз")
}
request := dto.ListChatsRequest{Limit: limit, Cursor: rawCursor}
userID := authenticatedUser(c).ID
position, err := h.cursorPosition(request.Cursor, cursorPresent, "chats", userID)
if err != nil {
return h.invalid(c, "Некорректный cursor")
}
page, err := h.useCase.ListChats(c.Request().Context(), userID, listChatsRequestToDomain(request, position))
if err != nil {
return h.useCaseError(c, err)
}
var next *string
if page.HasMore {
last := page.Items[len(page.Items)-1]
encoded := h.cursor.encode("chats", userID, last.CreatedAt, last.ID)
next = &encoded
}
return c.JSON(http.StatusOK, listChatsResponseFromDomain(page, next))
}
func listChatsRequestToDomain(request dto.ListChatsRequest, position *domain.Position) domain.Pagination {
return domain.Pagination{After: position, Limit: request.Limit}
}
func listChatsResponseFromDomain(page domain.ChatPage, nextCursor *string) dto.ListChatsResponse {
items := make([]dto.ListChatsItem, 0, len(page.Items))
for _, chat := range page.Items {
items = append(items, dto.ListChatsItem{
ID: chat.ID, Title: chat.Title, MemberIDs: chat.MemberIDs, CreatedAt: dto.Timestamp(chat.CreatedAt),
})
}
return dto.ListChatsResponse{Items: items, NextCursor: nextCursor}
}
+70
View File
@@ -0,0 +1,70 @@
package chat
import (
"net/http"
"github.com/labstack/echo/v4"
"gitflic.ru/akselbant/mtusi2026lab1-fork/dto"
"gitflic.ru/akselbant/mtusi2026lab1-fork/internal/pkg/domain"
)
func (h *Chat) listMessages(c echo.Context) error {
request := dto.ListMessagesRequest{ChatID: c.Param("chat_id")}
chat, ok, err := h.authorizedChat(c, domain.Chat{ID: request.ChatID})
if err != nil {
return err
}
if !ok {
return nil
}
limit, err := parseLimit(c)
if err != nil {
return h.invalid(c, err.Error())
}
rawCursor, cursorPresent, err := oneQueryValue(c, "cursor")
if err != nil {
return h.invalid(c, "cursor должен быть указан один раз")
}
request.ChatID = chat.ID
request.Limit = limit
request.Cursor = rawCursor
position, err := h.cursorPosition(request.Cursor, cursorPresent, "messages", request.ChatID)
if err != nil {
return h.invalid(c, "Некорректный cursor")
}
page, err := h.useCase.ListMessages(
c.Request().Context(), authenticatedUser(c).ID,
listMessagesChatToDomain(request), listMessagesPaginationToDomain(request, position),
)
if err != nil {
return h.useCaseError(c, err)
}
var next *string
if page.HasMore {
last := page.Items[len(page.Items)-1]
encoded := h.cursor.encode("messages", request.ChatID, last.CreatedAt, last.ID)
next = &encoded
}
return c.JSON(http.StatusOK, listMessagesResponseFromDomain(page, next))
}
func listMessagesChatToDomain(request dto.ListMessagesRequest) domain.Chat {
return domain.Chat{ID: request.ChatID}
}
func listMessagesPaginationToDomain(request dto.ListMessagesRequest, position *domain.Position) domain.Pagination {
return domain.Pagination{After: position, Limit: request.Limit}
}
func listMessagesResponseFromDomain(page domain.MessagePage, nextCursor *string) dto.ListMessagesResponse {
items := make([]dto.ListMessagesItem, 0, len(page.Items))
for _, message := range page.Items {
items = append(items, dto.ListMessagesItem{
ID: message.ID, ChatID: message.ChatID, SenderID: message.SenderID,
Text: message.Text, CreatedAt: dto.Timestamp(message.CreatedAt),
})
}
return dto.ListMessagesResponse{Items: items, NextCursor: nextCursor}
}
+13
View File
@@ -0,0 +1,13 @@
package chat
import (
"net/http"
"github.com/labstack/echo/v4"
"gitflic.ru/akselbant/mtusi2026lab1-fork/dto"
)
func (h *Chat) liveness(c echo.Context) error {
return c.JSON(http.StatusOK, dto.LivenessResponse{Status: "ok"})
}
+37
View File
@@ -0,0 +1,37 @@
package chat
import (
"github.com/google/uuid"
"github.com/labstack/echo/v4"
"gitflic.ru/akselbant/mtusi2026lab1-fork/internal/pkg/domain"
)
const (
requestIDKey = "request_id"
userKey = "current_user"
)
func (h *Chat) requestIDMiddleware(next echo.HandlerFunc) echo.HandlerFunc {
return func(c echo.Context) error {
requestID := uuid.NewString()
c.Set(requestIDKey, requestID)
c.Response().Header().Set("X-Request-Id", requestID)
return next(c)
}
}
func (h *Chat) authenticate(next echo.HandlerFunc) echo.HandlerFunc {
return func(c echo.Context) error {
user, err := h.useCase.Authenticate(c.Request().Context(), bearerToken(c))
if err != nil {
return h.useCaseError(c, err)
}
c.Set(userKey, user)
return next(c)
}
}
func authenticatedUser(c echo.Context) domain.User {
return c.Get(userKey).(domain.User)
}
+16
View File
@@ -0,0 +1,16 @@
package chat
import (
"net/http"
"github.com/labstack/echo/v4"
"gitflic.ru/akselbant/mtusi2026lab1-fork/dto"
)
func (h *Chat) readiness(c echo.Context) error {
if err := h.useCase.Ready(c.Request().Context()); err != nil {
return h.useCaseError(c, err)
}
return c.JSON(http.StatusOK, dto.ReadinessResponse{Status: "ok"})
}
+74
View File
@@ -0,0 +1,74 @@
package chat
import (
"encoding/json"
"errors"
"fmt"
"io"
"mime"
"net/http"
"strconv"
"github.com/labstack/echo/v4"
)
const (
defaultLimit = 50
maxLimit = 100
maxJSONBody = 1 << 20
)
var errUnsupportedMediaType = errors.New("unsupported media type")
func decodeJSON(c echo.Context, target any) error {
mediaType, _, err := mime.ParseMediaType(c.Request().Header.Get(echo.HeaderContentType))
if err != nil || mediaType != echo.MIMEApplicationJSON {
return errUnsupportedMediaType
}
reader := http.MaxBytesReader(c.Response(), c.Request().Body, maxJSONBody)
decoder := json.NewDecoder(reader)
decoder.DisallowUnknownFields()
if err := decoder.Decode(target); err != nil {
var tooLarge *http.MaxBytesError
if errors.As(err, &tooLarge) {
return err
}
return errors.New("Некорректное JSON-тело")
}
var extra any
err = decoder.Decode(&extra)
var tooLarge *http.MaxBytesError
if errors.As(err, &tooLarge) {
return err
}
if !errors.Is(err, io.EOF) {
return errors.New("JSON-тело должно содержать ровно один объект")
}
return nil
}
func parseLimit(c echo.Context) (int, error) {
raw, present, err := oneQueryValue(c, "limit")
if err != nil {
return 0, errors.New("limit должен быть указан один раз")
}
if !present {
return defaultLimit, nil
}
limit, err := strconv.Atoi(raw)
if err != nil || limit < 1 || limit > maxLimit {
return 0, fmt.Errorf("limit должен быть целым числом от 1 до %d", maxLimit)
}
return limit, nil
}
func oneQueryValue(c echo.Context, name string) (string, bool, error) {
values, present := c.QueryParams()[name]
if !present {
return "", false, nil
}
if len(values) != 1 {
return "", true, errors.New("query parameter must occur once")
}
return values[0], true, nil
}
+75
View File
@@ -0,0 +1,75 @@
package chat
import (
"log"
"github.com/labstack/echo/v4"
"github.com/labstack/echo/v4/middleware"
"github.com/swaggest/swgui/v5emb"
)
// Chat is the HTTP handler and depends only on the application boundary.
type Chat struct {
useCase UseCase
cursor cursorCodec
}
func NewChat(useCase UseCase, cursorKey [32]byte) *Chat {
return &Chat{useCase: useCase, cursor: cursorCodec{secret: cursorKey}}
}
func (h *Chat) Router() *echo.Echo {
e := echo.New()
e.HideBanner = true
e.HidePort = true
e.HTTPErrorHandler = h.httpErrorHandler
e.Use(h.requestIDMiddleware)
e.Use(middleware.RequestLoggerWithConfig(middleware.RequestLoggerConfig{
HandleError: true,
LogLatency: true,
LogMethod: true,
LogRoutePath: true,
LogURIPath: true,
LogRequestID: true,
LogStatus: true,
LogResponseSize: true,
LogValuesFunc: func(_ echo.Context, values middleware.RequestLoggerValues) error {
path := values.RoutePath
if path == "" {
path = values.URIPath
}
log.Printf(
"request_id=%s method=%s path=%s status=%d response_bytes=%d latency=%s",
values.RequestID, values.Method, path, values.Status, values.ResponseSize, values.Latency,
)
return nil
},
}))
e.Use(middleware.Recover())
e.GET("/health/live", h.liveness)
e.GET("/health/ready", h.readiness)
swaggerUI := echo.WrapHandler(v5emb.New(
"MTUSI Messenger",
"/swagger/openapi.json",
"/swagger/",
))
e.GET("/swagger", h.swagger)
e.GET("/swagger/", swaggerUI)
e.GET("/swagger/openapi.json", h.swaggerSpec)
e.GET("/swagger/*", swaggerUI)
e.POST("/api/v1/users", h.createUser)
e.POST("/api/v1/auth/sessions", h.createSession)
api := e.Group("/api/v1", h.authenticate)
api.GET("/users/me", h.currentUser)
api.DELETE("/auth/sessions/current", h.deleteSession)
api.POST("/chats", h.createChat)
api.GET("/chats", h.listChats)
api.GET("/chats/:chat_id", h.getChat)
api.POST("/chats/:chat_id/messages", h.createMessage)
api.GET("/chats/:chat_id/messages", h.listMessages)
return e
}
+349
View File
@@ -0,0 +1,349 @@
package chat_test
import (
"bytes"
"context"
"encoding/base64"
"encoding/json"
"fmt"
"io"
"net/http"
"net/http/httptest"
"net/url"
"sync"
"testing"
"time"
chathandler "gitflic.ru/akselbant/mtusi2026lab1-fork/internal/app/chat"
"gitflic.ru/akselbant/mtusi2026lab1-fork/internal/pkg/domain"
"gitflic.ru/akselbant/mtusi2026lab1-fork/internal/pkg/repository"
chatusecase "gitflic.ru/akselbant/mtusi2026lab1-fork/internal/usecase/chat"
)
type testAPI struct {
server *httptest.Server
tokens sync.Map
}
type userResponse struct {
ID string `json:"id"`
}
type chatResponse struct {
ID string `json:"id"`
}
type messageResponse struct {
ID string `json:"id"`
Text string `json:"text"`
}
type messagePageResponse struct {
Items []messageResponse `json:"items"`
NextCursor *string `json:"next_cursor"`
}
type errorResponse struct {
Error struct {
Code string `json:"code"`
} `json:"error"`
}
func newTestAPI(t *testing.T) *testAPI {
t.Helper()
useCase := chatusecase.New(repository.NewMemory(), &testSessions{values: map[string]domain.Session{}}, time.Hour)
server := httptest.NewServer(chathandler.NewChat(useCase, [32]byte{1}).Router())
t.Cleanup(server.Close)
return &testAPI{server: server}
}
func (a *testAPI) request(t *testing.T, client *http.Client, method, path, actorID, body string, wantStatus int, target any) {
t.Helper()
request, err := http.NewRequest(method, a.server.URL+path, bytes.NewBufferString(body))
if err != nil {
t.Fatalf("create request: %v", err)
}
if body != "" {
request.Header.Set("Content-Type", "application/json")
}
if actorID != "" {
token, _ := a.tokens.Load(actorID)
request.Header.Set("Authorization", "Bearer "+token.(string))
}
response, err := client.Do(request)
if err != nil {
t.Fatalf("%s %s: %v", method, path, err)
}
defer response.Body.Close()
responseBody, err := io.ReadAll(response.Body)
if err != nil {
t.Fatalf("read response: %v", err)
}
if response.StatusCode != wantStatus {
t.Fatalf("%s %s: status=%d, want=%d, body=%s", method, path, response.StatusCode, wantStatus, responseBody)
}
if response.Header.Get("X-Request-Id") == "" {
t.Fatalf("%s %s: missing X-Request-Id", method, path)
}
if target != nil {
if err := json.Unmarshal(responseBody, target); err != nil {
t.Fatalf("decode response %q: %v", responseBody, err)
}
}
}
func (a *testAPI) createUser(t *testing.T, username string) userResponse {
t.Helper()
var user userResponse
a.request(t, http.DefaultClient, http.MethodPost, "/api/v1/users", "",
fmt.Sprintf(`{"username":%q,"display_name":%q,"password":"test-password-12345"}`, username, username), http.StatusCreated, &user)
req, err := http.NewRequest(http.MethodPost, a.server.URL+"/api/v1/auth/sessions", nil)
if err != nil {
t.Fatal(err)
}
req.Header.Set("Authorization", "Basic "+base64.StdEncoding.EncodeToString([]byte(username+":test-password-12345")))
response, err := http.DefaultClient.Do(req)
if err != nil {
t.Fatal(err)
}
defer response.Body.Close()
var login struct {
Token string `json:"token"`
}
if response.StatusCode != http.StatusCreated {
t.Fatalf("login status: %d", response.StatusCode)
}
if err = json.NewDecoder(response.Body).Decode(&login); err != nil {
t.Fatal(err)
}
a.tokens.Store(user.ID, login.Token)
return user
}
func (a *testAPI) requestError(t *testing.T, method, path, actorID, body string, wantStatus int, wantCode string) {
t.Helper()
var response errorResponse
a.request(t, http.DefaultClient, method, path, actorID, body, wantStatus, &response)
if response.Error.Code != wantCode {
t.Fatalf("%s %s: error code=%q, want=%q", method, path, response.Error.Code, wantCode)
}
}
func (a *testAPI) createChat(t *testing.T, ownerID string, memberIDs []string) chatResponse {
t.Helper()
body, err := json.Marshal(map[string]any{"title": "test chat", "member_ids": memberIDs})
if err != nil {
t.Fatalf("encode chat: %v", err)
}
var chat chatResponse
a.request(t, http.DefaultClient, http.MethodPost, "/api/v1/chats", ownerID, string(body), http.StatusCreated, &chat)
return chat
}
func (a *testAPI) createMessage(t *testing.T, client *http.Client, actorID, chatID, text string) messageResponse {
t.Helper()
body, err := json.Marshal(map[string]string{"text": text})
if err != nil {
t.Fatalf("encode message: %v", err)
}
var message messageResponse
a.request(t, client, http.MethodPost, "/api/v1/chats/"+chatID+"/messages", actorID, string(body), http.StatusCreated, &message)
return message
}
func TestRejectsMalformedJSON(t *testing.T) {
api := newTestAPI(t)
api.requestError(t, http.MethodPost, "/api/v1/users", "",
`{"username":`, http.StatusBadRequest, "invalid_request")
}
func TestHidesForeignChat(t *testing.T) {
api := newTestAPI(t)
owner := api.createUser(t, "owner_user")
outsider := api.createUser(t, "outsider_user")
chat := api.createChat(t, owner.ID, []string{owner.ID})
api.requestError(t, http.MethodGet, "/api/v1/chats/"+chat.ID, outsider.ID,
"", http.StatusNotFound, "not_found")
}
func TestRejectsEmptyMessage(t *testing.T) {
api := newTestAPI(t)
user := api.createUser(t, "empty_message_user")
chat := api.createChat(t, user.ID, []string{user.ID})
api.requestError(t, http.MethodPost, "/api/v1/chats/"+chat.ID+"/messages", user.ID,
`{"text":" "}`, http.StatusBadRequest, "invalid_request")
}
func TestRejectsDuplicateUsername(t *testing.T) {
api := newTestAPI(t)
api.createUser(t, "duplicate_user")
api.requestError(t, http.MethodPost, "/api/v1/users", "",
`{"username":"duplicate_user","display_name":"Duplicate","password":"test-password-12345"}`, http.StatusConflict, "conflict")
}
func TestPaginatesMessagesAcrossMultiplePages(t *testing.T) {
api := newTestAPI(t)
user := api.createUser(t, "pagination_user")
chat := api.createChat(t, user.ID, []string{user.ID})
for index := 0; index < 7; index++ {
api.createMessage(t, http.DefaultClient, user.ID, chat.ID, fmt.Sprintf("message-%d", index))
}
seen := make(map[string]struct{})
cursor := ""
pageSizes := make([]int, 0, 4)
for {
path := "/api/v1/chats/" + chat.ID + "/messages?limit=2"
if cursor != "" {
path += "&cursor=" + url.QueryEscape(cursor)
}
var page messagePageResponse
api.request(t, http.DefaultClient, http.MethodGet, path, user.ID, "", http.StatusOK, &page)
pageSizes = append(pageSizes, len(page.Items))
for _, message := range page.Items {
if _, duplicate := seen[message.ID]; duplicate {
t.Fatalf("message %s appeared on multiple pages", message.ID)
}
seen[message.ID] = struct{}{}
}
if page.NextCursor == nil {
break
}
cursor = *page.NextCursor
}
if len(seen) != 7 {
t.Fatalf("received %d unique messages, want 7", len(seen))
}
wantPageSizes := []int{2, 2, 2, 1}
if fmt.Sprint(pageSizes) != fmt.Sprint(wantPageSizes) {
t.Fatalf("page sizes=%v, want=%v", pageSizes, wantPageSizes)
}
}
func TestConcurrentMessagesAreUnique(t *testing.T) {
api := newTestAPI(t)
users := make([]userResponse, 10)
memberIDs := make([]string, 10)
for index := range users {
users[index] = api.createUser(t, fmt.Sprintf("parallel_user_%02d", index))
memberIDs[index] = users[index].ID
}
chat := api.createChat(t, users[0].ID, memberIDs)
start := make(chan struct{})
errors := make(chan error, 10)
var waitGroup sync.WaitGroup
for clientIndex := 0; clientIndex < 10; clientIndex++ {
waitGroup.Add(1)
go func(clientIndex int) {
defer waitGroup.Done()
client := &http.Client{Transport: &http.Transport{}, Timeout: 5 * time.Second}
defer client.CloseIdleConnections()
<-start
for messageIndex := 0; messageIndex < 10; messageIndex++ {
body, err := json.Marshal(map[string]string{
"text": fmt.Sprintf("client-%02d-message-%02d", clientIndex, messageIndex),
})
if err != nil {
errors <- err
return
}
request, err := http.NewRequest(http.MethodPost,
api.server.URL+"/api/v1/chats/"+chat.ID+"/messages", bytes.NewReader(body))
if err != nil {
errors <- err
return
}
request.Header.Set("Content-Type", "application/json")
token, _ := api.tokens.Load(users[clientIndex].ID)
request.Header.Set("Authorization", "Bearer "+token.(string))
response, err := client.Do(request)
if err != nil {
errors <- err
return
}
_, readErr := io.Copy(io.Discard, response.Body)
closeErr := response.Body.Close()
if readErr != nil {
errors <- readErr
return
}
if closeErr != nil {
errors <- closeErr
return
}
if response.StatusCode != http.StatusCreated {
errors <- fmt.Errorf("client %d message %d: status=%d", clientIndex, messageIndex, response.StatusCode)
return
}
}
}(clientIndex)
}
close(start)
waitGroup.Wait()
close(errors)
for err := range errors {
if err != nil {
t.Fatal(err)
}
}
seenIDs := make(map[string]struct{}, 10*10)
seenTexts := make(map[string]struct{}, 10*10)
cursor := ""
for {
path := "/api/v1/chats/" + chat.ID + "/messages?limit=17"
if cursor != "" {
path += "&cursor=" + url.QueryEscape(cursor)
}
var page messagePageResponse
api.request(t, http.DefaultClient, http.MethodGet, path, users[0].ID, "", http.StatusOK, &page)
for _, message := range page.Items {
if _, duplicate := seenIDs[message.ID]; duplicate {
t.Fatalf("duplicate message ID %s", message.ID)
}
if _, duplicate := seenTexts[message.Text]; duplicate {
t.Fatalf("duplicate message text %q", message.Text)
}
seenIDs[message.ID] = struct{}{}
seenTexts[message.Text] = struct{}{}
}
if page.NextCursor == nil {
break
}
cursor = *page.NextCursor
}
if len(seenIDs) != 10*10 || len(seenTexts) != 10*10 {
t.Fatalf("received %d unique IDs and %d unique texts, want %d of each",
len(seenIDs), len(seenTexts), 10*10)
}
}
// Session fake is only used by HTTP unit tests; the server always uses Redis.
type testSessions struct {
mu sync.Mutex
values map[string]domain.Session
}
func (s *testSessions) Ready(context.Context) error { return nil }
func (s *testSessions) Put(_ context.Context, key string, value domain.Session) error {
s.mu.Lock()
defer s.mu.Unlock()
s.values[key] = value
return nil
}
func (s *testSessions) Get(_ context.Context, key string) (domain.Session, bool, error) {
s.mu.Lock()
defer s.mu.Unlock()
value, ok := s.values[key]
return value, ok, nil
}
func (s *testSessions) Delete(_ context.Context, key string) (bool, error) {
s.mu.Lock()
defer s.mu.Unlock()
_, ok := s.values[key]
delete(s.values, key)
return ok, nil
}
+45
View File
@@ -0,0 +1,45 @@
package chat
import (
"io"
"net/http"
"strings"
"github.com/labstack/echo/v4"
"gitflic.ru/akselbant/mtusi2026lab1-fork/dto"
)
func bearerToken(c echo.Context) string {
parts := strings.Fields(c.Request().Header.Get("Authorization"))
if len(parts) != 2 || !strings.EqualFold(parts[0], "Bearer") {
return ""
}
return parts[1]
}
func (h *Chat) createSession(c echo.Context) error {
username, password, ok := c.Request().BasicAuth()
if !ok {
c.Response().Header().Set("WWW-Authenticate", `Basic realm="messenger", charset="UTF-8"`)
return h.writeError(c, http.StatusUnauthorized, "unauthorized", "Неверные учётные данные")
}
body, err := io.ReadAll(io.LimitReader(c.Request().Body, 1))
if err != nil || len(body) != 0 {
return h.invalid(c, "Тело запроса входа должно быть пустым")
}
login, err := h.useCase.CreateSession(c.Request().Context(), username, password)
if err != nil {
return h.useCaseError(c, err)
}
return c.JSON(http.StatusCreated, dto.CreateSessionResponse{
Token: login.Token, TokenType: "Bearer", ExpiresAt: dto.Timestamp(login.ExpiresAt), User: createUserResponseFromDomain(login.User),
})
}
func (h *Chat) deleteSession(c echo.Context) error {
if err := h.useCase.DeleteSession(c.Request().Context(), bearerToken(c)); err != nil {
return h.useCaseError(c, err)
}
return c.NoContent(http.StatusNoContent)
}
+38
View File
@@ -0,0 +1,38 @@
package chat
import (
"encoding/json"
"net/http"
"github.com/labstack/echo/v4"
"gitflic.ru/akselbant/mtusi2026lab1-fork/contracts"
)
var swaggerOpenAPI = makeSwaggerOpenAPI()
func (h *Chat) swagger(c echo.Context) error {
return c.Redirect(http.StatusTemporaryRedirect, "/swagger/")
}
func (h *Chat) swaggerSpec(c echo.Context) error {
return c.Blob(http.StatusOK, echo.MIMEApplicationJSON, swaggerOpenAPI)
}
func makeSwaggerOpenAPI() []byte {
var document map[string]any
if err := json.Unmarshal(contracts.OpenAPI, &document); err != nil {
panic("cannot decode embedded OpenAPI contract: " + err.Error())
}
// A relative URL keeps Swagger requests on the same scheme, host and port
// as the UI. This also works behind a reverse proxy and on a custom PORT.
document["servers"] = []map[string]string{{
"url": "/",
"description": "Текущий адрес Swagger UI",
}}
encoded, err := json.Marshal(document)
if err != nil {
panic("cannot encode Swagger OpenAPI contract: " + err.Error())
}
return encoded
}
+21
View File
@@ -0,0 +1,21 @@
package chat
import (
"context"
"gitflic.ru/akselbant/mtusi2026lab1-fork/internal/pkg/domain"
)
// UseCase is the application boundary required by the HTTP handler.
type UseCase interface {
Ready(context.Context) error
CreateSession(context.Context, string, string) (domain.Login, error)
DeleteSession(context.Context, string) error
Authenticate(ctx context.Context, token string) (domain.User, error)
CreateUser(ctx context.Context, user domain.User, password string) (domain.User, error)
CreateChat(ctx context.Context, callerID string, chat domain.Chat) (domain.Chat, error)
GetChat(ctx context.Context, callerID string, chat domain.Chat) (domain.Chat, error)
ListChats(ctx context.Context, callerID string, pagination domain.Pagination) (domain.ChatPage, error)
CreateMessage(ctx context.Context, callerID string, message domain.Message) (domain.Message, error)
ListMessages(ctx context.Context, callerID string, chat domain.Chat, pagination domain.Pagination) (domain.MessagePage, error)
}
+100
View File
@@ -0,0 +1,100 @@
package config
import (
"encoding/hex"
"fmt"
"os"
"strconv"
"strings"
"time"
)
type Config struct {
Port string
PostgresHost string
PostgresPort uint16
PostgresUser string
PostgresDatabase string
PostgresPassword string
PostgresMaxConns int32
RedisAddr string
SessionTTL time.Duration
QueryTimeout time.Duration
CursorKey [32]byte
}
func value(name, fallback string) string {
if v := os.Getenv(name); v != "" {
return v
}
return fallback
}
func positive(name string, fallback, max int) (int, error) {
n, err := strconv.Atoi(value(name, strconv.Itoa(fallback)))
if err != nil || n < 1 || n > max {
return 0, fmt.Errorf("invalid %s", name)
}
return n, nil
}
func secret(name string) (string, error) {
if file := os.Getenv(name + "_FILE"); file != "" {
data, err := os.ReadFile(file)
if err != nil {
return "", fmt.Errorf("cannot read %s_FILE", name)
}
if s := strings.TrimSpace(string(data)); s != "" {
return s, nil
}
}
if s := os.Getenv(name); s != "" {
return s, nil
}
return "", fmt.Errorf("%s or %s_FILE is required", name, name)
}
func Load() (Config, error) {
var c Config
port, err := positive("PORT", 8080, 65535)
if err != nil {
return c, err
}
c.Port = strconv.Itoa(port)
pgPort, err := positive("POSTGRES_PORT", 5432, 65535)
if err != nil {
return c, err
}
c.PostgresPort = uint16(pgPort)
max, err := positive("POSTGRES_MAX_CONNS", 10, 100)
if err != nil {
return c, err
}
c.PostgresMaxConns = int32(max)
ttl, err := positive("SESSION_TTL_SECONDS", 3600, 86400*30)
if err != nil {
return c, err
}
c.SessionTTL = time.Duration(ttl) * time.Second
timeout, err := positive("QUERY_TIMEOUT_MS", 2000, 10000)
if err != nil {
return c, err
}
c.QueryTimeout = time.Duration(timeout) * time.Millisecond
c.PostgresHost = value("POSTGRES_HOST", "localhost")
c.PostgresUser = value("POSTGRES_USER", "messenger")
c.PostgresDatabase = value("POSTGRES_DB", "messenger")
c.RedisAddr = value("REDIS_ADDR", "localhost:6379")
c.PostgresPassword, err = secret("POSTGRES_PASSWORD")
if err != nil {
return c, err
}
key, err := secret("CURSOR_KEY")
if err != nil {
return c, err
}
decoded, err := hex.DecodeString(key)
if err != nil || len(decoded) != 32 {
return c, fmt.Errorf("CURSOR_KEY must be 32 random bytes encoded as hex")
}
copy(c.CursorKey[:], decoded)
return c, nil
}
+10
View File
@@ -0,0 +1,10 @@
package domain
import "time"
type Chat struct {
ID string
Title string
MemberIDs []string
CreatedAt time.Time
}
+32
View File
@@ -0,0 +1,32 @@
package domain
import "errors"
type ErrorCode string
const (
ErrorUnavailable ErrorCode = "unavailable"
ErrorInvalid ErrorCode = "invalid_request"
ErrorUnauthorized ErrorCode = "unauthorized"
ErrorNotFound ErrorCode = "not_found"
ErrorConflict ErrorCode = "conflict"
)
type ApplicationError struct {
Code ErrorCode
Message string
}
func (e *ApplicationError) Error() string {
return e.Message
}
func NewApplicationError(code ErrorCode, message string) error {
return &ApplicationError{Code: code, Message: message}
}
func AsApplicationError(err error) (*ApplicationError, bool) {
var applicationError *ApplicationError
ok := errors.As(err, &applicationError)
return applicationError, ok
}
+11
View File
@@ -0,0 +1,11 @@
package domain
import "time"
type Message struct {
ID string
ChatID string
SenderID string
Text string
CreatedAt time.Time
}
+23
View File
@@ -0,0 +1,23 @@
package domain
import "time"
type Position struct {
CreatedAt time.Time
ID string
}
type Pagination struct {
After *Position
Limit int
}
type ChatPage struct {
Items []Chat
HasMore bool
}
type MessagePage struct {
Items []Message
HasMore bool
}
+14
View File
@@ -0,0 +1,14 @@
package domain
import "time"
type Session struct {
UserID string `json:"user_id"`
ExpiresAt time.Time `json:"expires_at"`
}
type Login struct {
Token string
ExpiresAt time.Time
User User
}
+10
View File
@@ -0,0 +1,10 @@
package domain
import "time"
type User struct {
ID string
Username string
DisplayName string
CreatedAt time.Time
}
+65
View File
@@ -0,0 +1,65 @@
package password
import (
"context"
"crypto/rand"
"crypto/subtle"
"encoding/base64"
"errors"
"strings"
"golang.org/x/crypto/argon2"
)
// Bound simultaneous KDF work to 4 * 19 MiB, including concurrent registrations.
var slots = make(chan struct{}, 4)
const prefix = "$argon2id$v=19$m=19456,t=2,p=1$"
func derive(ctx context.Context, password string, salt []byte) ([]byte, error) {
select {
case slots <- struct{}{}:
case <-ctx.Done():
return nil, ctx.Err()
}
defer func() { <-slots }()
if err := ctx.Err(); err != nil {
return nil, err
}
return argon2.IDKey([]byte(password), salt, 2, 19456, 1, 32), nil
}
func Hash(ctx context.Context, password string) (string, error) {
salt := make([]byte, 16)
if _, err := rand.Read(salt); err != nil {
return "", err
}
key, err := derive(ctx, password, salt)
if err != nil {
return "", err
}
return prefix + base64.RawStdEncoding.EncodeToString(salt) + "$" + base64.RawStdEncoding.EncodeToString(key), nil
}
func Verify(ctx context.Context, password, encoded string) (bool, error) {
if !strings.HasPrefix(encoded, prefix) {
return false, errors.New("unsupported password hash")
}
parts := strings.Split(strings.TrimPrefix(encoded, prefix), "$")
if len(parts) != 2 {
return false, errors.New("invalid password hash")
}
salt, err := base64.RawStdEncoding.DecodeString(parts[0])
if err != nil || len(salt) != 16 {
return false, errors.New("invalid salt")
}
expected, err := base64.RawStdEncoding.DecodeString(parts[1])
if err != nil || len(expected) != 32 {
return false, errors.New("invalid hash")
}
actual, err := derive(ctx, password, salt)
return subtle.ConstantTimeCompare(actual, expected) == 1, err
}
// A valid fixed encoding for equal-cost verification when username does not exist.
const DummyHash = prefix + "AAAAAAAAAAAAAAAAAAAAAA$AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"
+35
View File
@@ -0,0 +1,35 @@
package password_test
import (
"context"
"strings"
"testing"
"gitflic.ru/akselbant/mtusi2026lab1-fork/internal/pkg/password"
)
func TestUnicodeAndSalt(t *testing.T) {
ctx := context.Background()
secret := strings.Repeat("🔑", 128)
first, err := password.Hash(ctx, secret)
if err != nil {
t.Fatal(err)
}
second, err := password.Hash(ctx, secret)
if err != nil {
t.Fatal(err)
}
if first == second {
t.Fatal("password hashes reused salt")
}
for _, hash := range []string{first, second} {
ok, err := password.Verify(ctx, secret, hash)
if err != nil || !ok {
t.Fatal("128-code-point UTF-8 password rejected")
}
ok, err = password.Verify(ctx, strings.Repeat("🔑", 127)+"x", hash)
if err != nil || ok {
t.Fatal("password suffix was ignored")
}
}
}
+191
View File
@@ -0,0 +1,191 @@
package repository
import (
"context"
"sort"
"sync"
"time"
"github.com/google/uuid"
"gitflic.ru/akselbant/mtusi2026lab1-fork/internal/pkg/domain"
chatusecase "gitflic.ru/akselbant/mtusi2026lab1-fork/internal/usecase/chat"
)
// Memory is the lab1 in-memory Repository implementation.
type Memory struct {
mu sync.RWMutex
users map[string]domain.User
hashes map[string]string
userByUsername map[string]string
chats map[string]domain.Chat
messages map[string][]domain.Message
}
var _ chatusecase.Repository = (*Memory)(nil)
func NewMemory() *Memory {
return &Memory{
users: make(map[string]domain.User),
hashes: make(map[string]string),
userByUsername: make(map[string]string),
chats: make(map[string]domain.Chat),
messages: make(map[string][]domain.Message),
}
}
func (m *Memory) CreateUser(_ context.Context, username, displayName, hash string) (domain.User, error) {
m.mu.Lock()
defer m.mu.Unlock()
if _, exists := m.userByUsername[username]; exists {
return domain.User{}, chatusecase.ErrUsernameTaken
}
user := domain.User{
ID: uuid.NewString(),
Username: username,
DisplayName: displayName,
CreatedAt: now(),
}
m.users[user.ID] = user
m.hashes[user.ID] = hash
m.userByUsername[user.Username] = user.ID
return user, nil
}
func (m *Memory) User(_ context.Context, id string) (domain.User, bool, error) {
m.mu.RLock()
defer m.mu.RUnlock()
user, ok := m.users[id]
return user, ok, nil
}
func (m *Memory) CreateChat(_ context.Context, title string, memberIDs []string) (domain.Chat, error) {
m.mu.Lock()
defer m.mu.Unlock()
for _, memberID := range memberIDs {
if _, exists := m.users[memberID]; !exists {
return domain.Chat{}, chatusecase.ErrUserNotFound
}
}
chat := domain.Chat{
ID: uuid.NewString(),
Title: title,
MemberIDs: append([]string(nil), memberIDs...),
CreatedAt: now(),
}
m.chats[chat.ID] = chat
return cloneChat(chat), nil
}
func (m *Memory) ChatForUser(_ context.Context, chatID, userID string) (domain.Chat, error) {
m.mu.RLock()
defer m.mu.RUnlock()
chat, exists := m.chats[chatID]
if !exists {
return domain.Chat{}, chatusecase.ErrChatNotFound
}
if !contains(chat.MemberIDs, userID) {
return domain.Chat{}, chatusecase.ErrNotMember
}
return cloneChat(chat), nil
}
func (m *Memory) ListChats(_ context.Context, userID string, after *domain.Position, limit int) ([]domain.Chat, error) {
m.mu.RLock()
defer m.mu.RUnlock()
result := make([]domain.Chat, 0)
for _, chat := range m.chats {
if contains(chat.MemberIDs, userID) && isAfter(chat.CreatedAt, chat.ID, after) {
result = append(result, cloneChat(chat))
}
}
sort.Slice(result, func(i, j int) bool {
return less(result[i].CreatedAt, result[i].ID, result[j].CreatedAt, result[j].ID)
})
if len(result) > limit {
result = result[:limit]
}
return result, nil
}
func (m *Memory) CreateMessage(_ context.Context, chatID, senderID, text string) (domain.Message, error) {
m.mu.Lock()
defer m.mu.Unlock()
chat, exists := m.chats[chatID]
if !exists {
return domain.Message{}, chatusecase.ErrChatNotFound
}
if !contains(chat.MemberIDs, senderID) {
return domain.Message{}, chatusecase.ErrNotMember
}
message := domain.Message{
ID: uuid.NewString(),
ChatID: chatID,
SenderID: senderID,
Text: text,
CreatedAt: now(),
}
m.messages[chatID] = append(m.messages[chatID], message)
return message, nil
}
func (m *Memory) ListMessages(_ context.Context, chatID string, after *domain.Position, limit int) ([]domain.Message, error) {
m.mu.RLock()
defer m.mu.RUnlock()
values := m.messages[chatID]
result := make([]domain.Message, 0, min(len(values), limit))
for _, message := range values {
if isAfter(message.CreatedAt, message.ID, after) {
result = append(result, message)
}
}
sort.Slice(result, func(i, j int) bool {
return less(result[i].CreatedAt, result[i].ID, result[j].CreatedAt, result[j].ID)
})
if len(result) > limit {
result = result[:limit]
}
return result, nil
}
func cloneChat(chat domain.Chat) domain.Chat {
chat.MemberIDs = append([]string(nil), chat.MemberIDs...)
return chat
}
func now() time.Time {
return time.Now().UTC().Truncate(time.Second)
}
func contains(values []string, target string) bool {
for _, value := range values {
if value == target {
return true
}
}
return false
}
func isAfter(createdAt time.Time, id string, after *domain.Position) bool {
return after == nil || createdAt.After(after.CreatedAt) || createdAt.Equal(after.CreatedAt) && id > after.ID
}
func less(leftTime time.Time, leftID string, rightTime time.Time, rightID string) bool {
if leftTime.Equal(rightTime) {
return leftID < rightID
}
return leftTime.Before(rightTime)
}
func (m *Memory) Ready(context.Context) error { return nil }
func (m *Memory) UserByUsername(_ context.Context, username string) (domain.User, string, bool, error) {
m.mu.RLock()
defer m.mu.RUnlock()
id, ok := m.userByUsername[username]
return m.users[id], m.hashes[id], ok, nil
}
+78
View File
@@ -0,0 +1,78 @@
package postgres
import (
"context"
"errors"
"github.com/google/uuid"
"github.com/jackc/pgx/v5"
"gitflic.ru/akselbant/mtusi2026lab1-fork/internal/pkg/domain"
chatusecase "gitflic.ru/akselbant/mtusi2026lab1-fork/internal/usecase/chat"
)
func (s *Storage) CreateChat(ctx context.Context, title string, members []string) (domain.Chat, error) {
ctx, cancel := context.WithTimeout(ctx, s.timeout)
defer cancel()
tx, err := s.pool.Begin(ctx)
if err != nil {
return domain.Chat{}, dbError(err)
}
defer tx.Rollback(context.WithoutCancel(ctx))
chat := domain.Chat{ID: uuid.NewString(), Title: title, MemberIDs: append([]string(nil), members...)}
err = tx.QueryRow(ctx, `INSERT INTO chats(id,title) VALUES($1,$2) RETURNING created_at`, chat.ID, title).Scan(&chat.CreatedAt)
if err != nil {
return domain.Chat{}, dbError(err)
}
for i, member := range members {
if _, err = tx.Exec(ctx, `INSERT INTO chat_members(chat_id,user_id,ordinal) VALUES($1,$2,$3)`, chat.ID, member, i); err != nil {
return domain.Chat{}, dbError(err)
}
}
if err = tx.Commit(ctx); err != nil {
return domain.Chat{}, dbError(err)
}
return chat, nil
}
const chatColumns = `c.id::text,c.title,c.created_at,ARRAY(SELECT m.user_id::text FROM chat_members m WHERE m.chat_id=c.id ORDER BY m.ordinal)`
func (s *Storage) ChatForUser(ctx context.Context, chatID, userID string) (domain.Chat, error) {
ctx, cancel := context.WithTimeout(ctx, s.timeout)
defer cancel()
var chat domain.Chat
err := s.pool.QueryRow(ctx, `SELECT `+chatColumns+` FROM chats c
WHERE c.id=$1 AND EXISTS(SELECT 1 FROM chat_members m WHERE m.chat_id=c.id AND m.user_id=$2)`, chatID, userID).
Scan(&chat.ID, &chat.Title, &chat.CreatedAt, &chat.MemberIDs)
if errors.Is(err, pgx.ErrNoRows) {
return chat, chatusecase.ErrChatNotFound
}
return chat, dbError(err)
}
func (s *Storage) ListChats(ctx context.Context, userID string, after *domain.Position, limit int) ([]domain.Chat, error) {
ctx, cancel := context.WithTimeout(ctx, s.timeout)
defer cancel()
query := `SELECT ` + chatColumns + ` FROM chats c JOIN chat_members member ON member.chat_id=c.id
WHERE member.user_id=$1`
args := []any{userID, limit}
if after != nil {
query += ` AND (c.created_at,c.id)>($3,$4)`
args = append(args, after.CreatedAt, after.ID)
}
query += ` ORDER BY c.created_at,c.id LIMIT $2`
rows, err := s.pool.Query(ctx, query, args...)
if err != nil {
return nil, dbError(err)
}
defer rows.Close()
chats := make([]domain.Chat, 0)
for rows.Next() {
var chat domain.Chat
if err = rows.Scan(&chat.ID, &chat.Title, &chat.CreatedAt, &chat.MemberIDs); err != nil {
return nil, dbError(err)
}
chats = append(chats, chat)
}
return chats, dbError(rows.Err())
}
@@ -0,0 +1,44 @@
package postgres
import (
"context"
"github.com/google/uuid"
"gitflic.ru/akselbant/mtusi2026lab1-fork/internal/pkg/domain"
)
func (s *Storage) CreateMessage(ctx context.Context, chatID, senderID, text string) (domain.Message, error) {
ctx, cancel := context.WithTimeout(ctx, s.timeout)
defer cancel()
message := domain.Message{ID: uuid.NewString(), ChatID: chatID, SenderID: senderID, Text: text}
err := s.pool.QueryRow(ctx, `INSERT INTO messages(id,chat_id,sender_id,text) VALUES($1,$2,$3,$4) RETURNING created_at`,
message.ID, chatID, senderID, text).Scan(&message.CreatedAt)
return message, dbError(err)
}
func (s *Storage) ListMessages(ctx context.Context, chatID string, after *domain.Position, limit int) ([]domain.Message, error) {
ctx, cancel := context.WithTimeout(ctx, s.timeout)
defer cancel()
query := `SELECT m.id::text,m.chat_id::text,m.sender_id::text,m.text,m.created_at FROM messages m WHERE m.chat_id=$1`
args := []any{chatID, limit}
if after != nil {
query += ` AND (m.created_at,m.id)>($3,$4)`
args = append(args, after.CreatedAt, after.ID)
}
query += ` ORDER BY m.created_at,m.id LIMIT $2`
rows, err := s.pool.Query(ctx, query, args...)
if err != nil {
return nil, dbError(err)
}
defer rows.Close()
messages := make([]domain.Message, 0)
for rows.Next() {
var m domain.Message
if err = rows.Scan(&m.ID, &m.ChatID, &m.SenderID, &m.Text, &m.CreatedAt); err != nil {
return nil, dbError(err)
}
messages = append(messages, m)
}
return messages, dbError(rows.Err())
}
@@ -0,0 +1,51 @@
package postgres
import (
"context"
"errors"
"log"
"time"
"github.com/jackc/pgx/v5"
"github.com/jackc/pgx/v5/pgconn"
"github.com/jackc/pgx/v5/pgxpool"
"gitflic.ru/akselbant/mtusi2026lab1-fork/internal/pkg/domain"
chatusecase "gitflic.ru/akselbant/mtusi2026lab1-fork/internal/usecase/chat"
)
type Storage struct {
pool *pgxpool.Pool
timeout time.Duration
}
var _ chatusecase.Repository = (*Storage)(nil)
func New(pool *pgxpool.Pool, timeout time.Duration) *Storage {
return &Storage{pool: pool, timeout: timeout}
}
func (s *Storage) Ready(ctx context.Context) error {
ctx, cancel := context.WithTimeout(ctx, s.timeout)
defer cancel()
return dbError(s.pool.Ping(ctx))
}
func dbError(err error) error {
if err == nil {
return nil
}
var pgErr *pgconn.PgError
if errors.As(err, &pgErr) {
switch pgErr.Code {
case "23505":
return chatusecase.ErrUsernameTaken
case "23503":
return chatusecase.ErrUserNotFound
}
log.Printf("postgres operation failed: sqlstate=%s", pgErr.Code)
} else if !errors.Is(err, pgx.ErrNoRows) {
log.Print("postgres operation failed")
}
return domain.NewApplicationError(domain.ErrorUnavailable, "Хранилище недоступно")
}
@@ -0,0 +1,232 @@
package postgres_test
import (
"context"
"errors"
"net"
"net/url"
"os"
"os/exec"
"path/filepath"
"strconv"
"strings"
"sync"
"testing"
"time"
"github.com/google/uuid"
"github.com/jackc/pgx/v5/pgxpool"
"gitflic.ru/akselbant/mtusi2026lab1-fork/internal/config"
"gitflic.ru/akselbant/mtusi2026lab1-fork/internal/pkg/domain"
"gitflic.ru/akselbant/mtusi2026lab1-fork/internal/pkg/repository/postgres"
chatusecase "gitflic.ru/akselbant/mtusi2026lab1-fork/internal/usecase/chat"
)
func TestIntegration(t *testing.T) {
if os.Getenv("INTEGRATION_TESTS") != "1" {
t.Skip("run make test-integration against the Compose stack")
}
ctx := context.Background()
cfg, err := config.Load()
if err != nil {
t.Fatal(err)
}
pc, err := pgxpool.ParseConfig("sslmode=disable")
if err != nil {
t.Fatal(err)
}
pc.ConnConfig.Host = cfg.PostgresHost
pc.ConnConfig.Port = cfg.PostgresPort
pc.ConnConfig.User = cfg.PostgresUser
pc.ConnConfig.Database = cfg.PostgresDatabase
pc.ConnConfig.Password = cfg.PostgresPassword
pc.ConnConfig.RuntimeParams["timezone"] = "UTC"
pc.MaxConns = 4
admin, err := pgxpool.NewWithConfig(ctx, pc.Copy())
if err != nil {
t.Fatal("connect failed")
}
defer admin.Close()
// Identifier is generated by the test, never from an API request.
schema := "test_" + uuid.New().String()[:8]
if _, err = admin.Exec(ctx, `CREATE SCHEMA `+schema); err != nil {
t.Fatal(err)
}
defer admin.Exec(ctx, `DROP SCHEMA `+schema+` CASCADE`)
pc.ConnConfig.RuntimeParams["search_path"] = schema
pool, err := pgxpool.NewWithConfig(ctx, pc)
if err != nil {
t.Fatal(err)
}
defer pool.Close()
runGoose := func(t *testing.T, command string) {
t.Helper()
migrationDir := os.Getenv("GOOSE_MIGRATION_DIR")
if migrationDir == "" {
migrationDir, err = filepath.Abs("../../../../migrations")
if err != nil {
t.Fatal(err)
}
}
connection := url.URL{Scheme: "postgres", User: url.User(cfg.PostgresUser), Host: net.JoinHostPort(cfg.PostgresHost, strconv.Itoa(int(cfg.PostgresPort))), Path: cfg.PostgresDatabase}
connection.RawQuery = url.Values{"sslmode": {"disable"}, "search_path": {schema}, "connect_timeout": {"5"}}.Encode()
commandCtx, cancel := context.WithTimeout(ctx, 45*time.Second)
defer cancel()
commandExec := exec.CommandContext(commandCtx, "goose", "-env", "/dev/null", "-dir", migrationDir, "-timeout", "30s", command)
commandExec.Env = append(os.Environ(), "GOOSE_DRIVER=postgres", "GOOSE_DBSTRING="+connection.String(), "PGPASSWORD="+cfg.PostgresPassword)
output, err := commandExec.CombinedOutput()
if err != nil {
t.Fatalf("goose %s: %v: %s", command, err, strings.ReplaceAll(string(output), cfg.PostgresPassword, "[redacted]"))
}
t.Logf("goose %s: %s", command, output)
}
runGoose(t, "up")
runGoose(t, "up")
var versions int
if err = pool.QueryRow(ctx, `SELECT count(*) FROM goose_db_version WHERE version_id=1 AND is_applied`).Scan(&versions); err != nil || versions != 1 {
t.Fatalf("migration versions=%d error=%v", versions, err)
}
repo := postgres.New(pool, 2*time.Second)
t.Run("registration_race", func(t *testing.T) {
const count = 12
results := make(chan error, count)
var wg sync.WaitGroup
start := make(chan struct{})
for i := 0; i < count; i++ {
wg.Add(1)
go func() {
defer wg.Done()
<-start
_, err := repo.CreateUser(ctx, "same_username", "Same", "test-hash")
results <- err
}()
}
close(start)
wg.Wait()
close(results)
successes, conflicts := 0, 0
for err := range results {
if err == nil {
successes++
} else if errors.Is(err, chatusecase.ErrUsernameTaken) {
conflicts++
} else {
t.Fatal(err)
}
}
if successes != 1 || conflicts != count-1 {
t.Fatalf("successes=%d conflicts=%d", successes, conflicts)
}
t.Logf("12 concurrent INSERTs: %d success, %d unique conflicts", successes, conflicts)
})
user, err := repo.CreateUser(ctx, "history_owner", "Owner", "test-hash")
if err != nil {
t.Fatal(err)
}
t.Run("rollback", func(t *testing.T) {
_, err := repo.CreateChat(ctx, "must rollback", []string{user.ID, uuid.NewString()})
if !errors.Is(err, chatusecase.ErrUserNotFound) {
t.Fatalf("unexpected error %v", err)
}
var chats, members int
if err = pool.QueryRow(ctx, `SELECT (SELECT count(*) FROM chats),(SELECT count(*) FROM chat_members)`).Scan(&chats, &members); err != nil {
t.Fatal(err)
}
if chats != 0 || members != 0 {
t.Fatalf("partial transaction: chats=%d members=%d", chats, members)
}
t.Log("failed second member INSERT left 0 chats and 0 members")
})
chat, err := repo.CreateChat(ctx, "History", []string{user.ID})
if err != nil {
t.Fatal(err)
}
_, err = pool.Exec(ctx, `INSERT INTO messages(id,chat_id,sender_id,text,created_at)
SELECT md5(i::text)::uuid,$1,$2,'synthetic message '||i,
timestamptz '2026-01-01 00:00:00+00' + (i / 10) * interval '1 millisecond'
FROM generate_series(1,10000) i`, chat.ID, user.ID)
if err != nil {
t.Fatal(err)
}
if _, err = pool.Exec(ctx, `ANALYZE messages`); err != nil {
t.Fatal(err)
}
t.Run("keyset_and_explain", func(t *testing.T) {
seen := make(map[string]bool)
var after *domain.Position
for {
page, err := repo.ListMessages(ctx, chat.ID, after, 97)
if err != nil {
t.Fatal(err)
}
if len(page) == 0 {
break
}
for _, message := range page {
if seen[message.ID] {
t.Fatal("duplicate on page boundary")
}
seen[message.ID] = true
}
last := page[len(page)-1]
after = &domain.Position{CreatedAt: last.CreatedAt, ID: last.ID}
}
if len(seen) != 10000 {
t.Fatalf("history count=%d", len(seen))
}
rows, err := pool.Query(ctx, `EXPLAIN (ANALYZE, BUFFERS)
SELECT m.id::text,m.chat_id::text,m.sender_id::text,m.text,m.created_at FROM messages m
WHERE m.chat_id=$1 AND (m.created_at,m.id)>($2,$3) ORDER BY m.created_at,m.id LIMIT $4`,
chat.ID, time.Date(2026, 1, 1, 0, 0, 0, 900000000, time.UTC), "00000000-0000-0000-0000-000000000000", 51)
if err != nil {
t.Fatal(err)
}
defer rows.Close()
t.Log("EXPLAIN on 10,000 messages, cursor near the end (9,000):")
for rows.Next() {
var line string
if err = rows.Scan(&line); err != nil {
t.Fatal(err)
}
t.Log(line)
}
if err = rows.Err(); err != nil {
t.Fatal(err)
}
t.Log("keyset traversal returned 10,000 distinct messages, including equal timestamps")
})
t.Run("goose_legacy_and_down", func(t *testing.T) {
// This is the disposable test schema, never the application's public schema.
const digestSQL = `SELECT md5(string_agg(ROW(id,chat_id,sender_id,text,created_at)::text,',' ORDER BY id)) FROM messages`
var before, after string
if err = pool.QueryRow(ctx, digestSQL).Scan(&before); err != nil {
t.Fatal(err)
}
if _, err = pool.Exec(ctx, `DROP TABLE goose_db_version;
CREATE TABLE schema_migrations(version text PRIMARY KEY,applied_at timestamptz NOT NULL DEFAULT now());
INSERT INTO schema_migrations(version) VALUES('001_initial.sql')`); err != nil {
t.Fatal(err)
}
runGoose(t, "up")
runGoose(t, "up")
if err = pool.QueryRow(ctx, digestSQL).Scan(&after); err != nil {
t.Fatal(err)
}
if before != after {
t.Fatal("legacy migration changed message data")
}
t.Log("adopted legacy schema: all 10,000 messages are unchanged")
runGoose(t, "down")
var tables int
if err = pool.QueryRow(ctx, `SELECT count(*) FROM information_schema.tables WHERE table_schema=$1 AND table_name IN ('users','chats','chat_members','messages','schema_migrations')`, schema).Scan(&tables); err != nil || tables != 0 {
t.Fatalf("down left %d application tables: %v", tables, err)
}
runGoose(t, "up")
if err = pool.QueryRow(ctx, `SELECT count(*) FROM messages`).Scan(&tables); err != nil || tables != 0 {
t.Fatalf("up after down failed: %v", err)
}
t.Log("down and up succeeded in isolated schema")
})
}
+46
View File
@@ -0,0 +1,46 @@
package postgres
import (
"context"
"errors"
"github.com/google/uuid"
"github.com/jackc/pgx/v5"
"gitflic.ru/akselbant/mtusi2026lab1-fork/internal/pkg/domain"
)
func (s *Storage) CreateUser(ctx context.Context, username, displayName, hash string) (domain.User, error) {
ctx, cancel := context.WithTimeout(ctx, s.timeout)
defer cancel()
var user domain.User
err := s.pool.QueryRow(ctx, `INSERT INTO users(id,username,display_name,password_hash) VALUES($1,$2,$3,$4)
RETURNING id::text,username,display_name,created_at`, uuid.NewString(), username, displayName, hash).
Scan(&user.ID, &user.Username, &user.DisplayName, &user.CreatedAt)
return user, dbError(err)
}
func (s *Storage) User(ctx context.Context, id string) (domain.User, bool, error) {
ctx, cancel := context.WithTimeout(ctx, s.timeout)
defer cancel()
var user domain.User
err := s.pool.QueryRow(ctx, `SELECT id::text,username,display_name,created_at FROM users WHERE id=$1`, id).
Scan(&user.ID, &user.Username, &user.DisplayName, &user.CreatedAt)
if errors.Is(err, pgx.ErrNoRows) {
return user, false, nil
}
return user, err == nil, dbError(err)
}
func (s *Storage) UserByUsername(ctx context.Context, username string) (domain.User, string, bool, error) {
ctx, cancel := context.WithTimeout(ctx, s.timeout)
defer cancel()
var user domain.User
var hash string
err := s.pool.QueryRow(ctx, `SELECT id::text,username,display_name,created_at,password_hash FROM users WHERE username=$1`, username).
Scan(&user.ID, &user.Username, &user.DisplayName, &user.CreatedAt, &hash)
if errors.Is(err, pgx.ErrNoRows) {
return user, "", false, nil
}
return user, hash, err == nil, dbError(err)
}
+71
View File
@@ -0,0 +1,71 @@
package session
import (
"context"
"encoding/json"
"errors"
"log"
"time"
"github.com/redis/go-redis/v9"
"gitflic.ru/akselbant/mtusi2026lab1-fork/internal/pkg/domain"
)
type Redis struct {
client *redis.Client
timeout time.Duration
}
func NewRedis(client *redis.Client, timeout time.Duration) *Redis {
return &Redis{client: client, timeout: timeout}
}
func unavailable(err error) error {
if err == nil {
return nil
}
log.Print("redis operation failed")
return domain.NewApplicationError(domain.ErrorUnavailable, "Хранилище сессий недоступно")
}
func (s *Redis) Ready(ctx context.Context) error {
ctx, cancel := context.WithTimeout(ctx, s.timeout)
defer cancel()
return unavailable(s.client.Ping(ctx).Err())
}
func (s *Redis) Put(ctx context.Context, key string, value domain.Session) error {
ctx, cancel := context.WithTimeout(ctx, s.timeout)
defer cancel()
data, err := json.Marshal(value)
if err != nil {
return err
}
// Absolute expiry prevents TTL extension by network delay or restart.
return unavailable(s.client.Do(ctx, "SET", "session:"+key, data, "PXAT", value.ExpiresAt.UnixMilli()).Err())
}
func (s *Redis) Get(ctx context.Context, key string) (domain.Session, bool, error) {
ctx, cancel := context.WithTimeout(ctx, s.timeout)
defer cancel()
var value domain.Session
data, err := s.client.Get(ctx, "session:"+key).Bytes()
if errors.Is(err, redis.Nil) {
return value, false, nil
}
if err != nil {
return value, false, unavailable(err)
}
if err = json.Unmarshal(data, &value); err != nil {
return value, false, unavailable(err)
}
return value, time.Now().Before(value.ExpiresAt), nil
}
func (s *Redis) Delete(ctx context.Context, key string) (bool, error) {
ctx, cancel := context.WithTimeout(ctx, s.timeout)
defer cancel()
count, err := s.client.Del(ctx, "session:"+key).Result()
return count > 0, unavailable(err)
}
+28
View File
@@ -0,0 +1,28 @@
package chat
import (
"context"
"errors"
"gitflic.ru/akselbant/mtusi2026lab1-fork/internal/pkg/domain"
)
var (
ErrUsernameTaken = errors.New("username is already taken")
ErrUserNotFound = errors.New("user not found")
ErrChatNotFound = errors.New("chat not found")
ErrNotMember = errors.New("user is not a chat member")
)
// Repository is the persistence port required by the chat use case.
type Repository interface {
Ready(ctx context.Context) error
UserByUsername(ctx context.Context, username string) (domain.User, string, bool, error)
CreateUser(ctx context.Context, username, displayName, passwordHash string) (domain.User, error)
User(ctx context.Context, id string) (domain.User, bool, error)
CreateChat(ctx context.Context, title string, memberIDs []string) (domain.Chat, error)
ChatForUser(ctx context.Context, chatID, userID string) (domain.Chat, error)
ListChats(ctx context.Context, userID string, after *domain.Position, limit int) ([]domain.Chat, error)
CreateMessage(ctx context.Context, chatID, senderID, text string) (domain.Message, error)
ListMessages(ctx context.Context, chatID string, after *domain.Position, limit int) ([]domain.Message, error)
}
+158
View File
@@ -0,0 +1,158 @@
package chat
import (
"context"
"errors"
"time"
"gitflic.ru/akselbant/mtusi2026lab1-fork/internal/pkg/domain"
"gitflic.ru/akselbant/mtusi2026lab1-fork/internal/pkg/password"
)
type UseCase struct {
repository Repository
sessions Sessions
sessionTTL time.Duration
}
func New(repository Repository, sessions Sessions, ttl time.Duration) *UseCase {
return &UseCase{repository: repository, sessions: sessions, sessionTTL: ttl}
}
func (u *UseCase) CreateUser(ctx context.Context, user domain.User, secret string) (domain.User, error) {
if !validUsername(user.Username) {
return domain.User{}, invalid("username должен соответствовать [a-z0-9_]{3,32}")
}
if !validRequiredText(user.DisplayName, 100) {
return domain.User{}, invalid("display_name должен содержать от 1 до 100 символов")
}
if !validPassword(secret) {
return domain.User{}, invalid("password должен содержать от 12 до 128 символов")
}
hash, err := password.Hash(ctx, secret)
if err != nil {
return domain.User{}, err
}
created, err := u.repository.CreateUser(ctx, user.Username, user.DisplayName, hash)
if errors.Is(err, ErrUsernameTaken) {
return domain.User{}, domain.NewApplicationError(domain.ErrorConflict, "Пользователь с таким username уже существует")
}
return created, err
}
func (u *UseCase) CreateChat(ctx context.Context, callerID string, chat domain.Chat) (domain.Chat, error) {
if !validRequiredText(chat.Title, 100) {
return domain.Chat{}, invalid("title должен содержать от 1 до 100 символов")
}
if len(chat.MemberIDs) < 1 || len(chat.MemberIDs) > 100 {
return domain.Chat{}, invalid("member_ids должен содержать от 1 до 100 участников")
}
normalizedIDs := make([]string, len(chat.MemberIDs))
seen := make(map[string]struct{}, len(chat.MemberIDs))
callerIncluded := false
for index, memberID := range chat.MemberIDs {
normalized, valid := normalizeUUID(memberID)
if !valid {
return domain.Chat{}, invalid("member_ids содержит некорректный UUID")
}
if _, duplicate := seen[normalized]; duplicate {
return domain.Chat{}, invalid("member_ids содержит повторяющиеся UUID")
}
normalizedIDs[index] = normalized
seen[normalized] = struct{}{}
callerIncluded = callerIncluded || normalized == callerID
}
if !callerIncluded {
return domain.Chat{}, invalid("текущий пользователь должен входить в member_ids")
}
created, err := u.repository.CreateChat(ctx, chat.Title, normalizedIDs)
if errors.Is(err, ErrUserNotFound) {
return domain.Chat{}, invalid("member_ids содержит неизвестного пользователя")
}
return created, err
}
func (u *UseCase) GetChat(ctx context.Context, callerID string, chat domain.Chat) (domain.Chat, error) {
chatID, valid := normalizeUUID(chat.ID)
if !valid {
return domain.Chat{}, invalid("Некорректный chat_id")
}
return u.chatForUser(ctx, chatID, callerID)
}
func (u *UseCase) ListChats(ctx context.Context, callerID string, pagination domain.Pagination) (domain.ChatPage, error) {
if pagination.Limit < 1 || pagination.Limit > 100 {
return domain.ChatPage{}, invalid("limit должен быть целым числом от 1 до 100")
}
items, err := u.repository.ListChats(ctx, callerID, pagination.After, pagination.Limit+1)
if err != nil {
return domain.ChatPage{}, err
}
page := domain.ChatPage{Items: items, HasMore: len(items) > pagination.Limit}
if page.HasMore {
page.Items = page.Items[:pagination.Limit]
}
return page, nil
}
func (u *UseCase) CreateMessage(ctx context.Context, callerID string, message domain.Message) (domain.Message, error) {
chatID, valid := normalizeUUID(message.ChatID)
if !valid {
return domain.Message{}, invalid("Некорректный chat_id")
}
if _, err := u.chatForUser(ctx, chatID, callerID); err != nil {
return domain.Message{}, err
}
if !validRequiredText(message.Text, 4000) {
return domain.Message{}, invalid("text должен содержать от 1 до 4000 символов")
}
created, err := u.repository.CreateMessage(ctx, chatID, callerID, message.Text)
if errors.Is(err, ErrChatNotFound) || errors.Is(err, ErrNotMember) {
return domain.Message{}, notFound()
}
return created, err
}
func (u *UseCase) ListMessages(ctx context.Context, callerID string, chat domain.Chat, pagination domain.Pagination) (domain.MessagePage, error) {
chatID, valid := normalizeUUID(chat.ID)
if !valid {
return domain.MessagePage{}, invalid("Некорректный chat_id")
}
if _, err := u.chatForUser(ctx, chatID, callerID); err != nil {
return domain.MessagePage{}, err
}
if pagination.Limit < 1 || pagination.Limit > 100 {
return domain.MessagePage{}, invalid("limit должен быть целым числом от 1 до 100")
}
items, err := u.repository.ListMessages(ctx, chatID, pagination.After, pagination.Limit+1)
if err != nil {
return domain.MessagePage{}, err
}
page := domain.MessagePage{Items: items, HasMore: len(items) > pagination.Limit}
if page.HasMore {
page.Items = page.Items[:pagination.Limit]
}
return page, nil
}
func (u *UseCase) chatForUser(ctx context.Context, chatID, callerID string) (domain.Chat, error) {
chat, err := u.repository.ChatForUser(ctx, chatID, callerID)
if errors.Is(err, ErrChatNotFound) || errors.Is(err, ErrNotMember) {
return domain.Chat{}, notFound()
}
return chat, err
}
func invalid(message string) error {
return domain.NewApplicationError(domain.ErrorInvalid, message)
}
func unauthorized() error {
return domain.NewApplicationError(domain.ErrorUnauthorized, "Требуется действительная сессия")
}
func notFound() error {
return domain.NewApplicationError(domain.ErrorNotFound, "Объект не найден")
}
+102
View File
@@ -0,0 +1,102 @@
package chat
import (
"context"
"crypto/rand"
"crypto/sha256"
"encoding/base64"
"encoding/hex"
"strings"
"time"
"unicode/utf8"
"gitflic.ru/akselbant/mtusi2026lab1-fork/internal/pkg/domain"
"gitflic.ru/akselbant/mtusi2026lab1-fork/internal/pkg/password"
)
type Sessions interface {
Put(context.Context, string, domain.Session) error
Get(context.Context, string) (domain.Session, bool, error)
Delete(context.Context, string) (bool, error)
Ready(context.Context) error
}
func validPassword(value string) bool {
n := utf8.RuneCountInString(value)
return utf8.ValidString(value) && n >= 12 && n <= 128 && strings.TrimSpace(value) != ""
}
func tokenKey(token string) string {
sum := sha256.Sum256([]byte(token))
return hex.EncodeToString(sum[:])
}
func (u *UseCase) Authenticate(ctx context.Context, token string) (domain.User, error) {
decoded, err := base64.RawURLEncoding.DecodeString(token)
if err != nil || len(decoded) != 32 {
return domain.User{}, unauthorized()
}
session, exists, err := u.sessions.Get(ctx, tokenKey(token))
if err != nil {
return domain.User{}, err
}
if !exists || !time.Now().Before(session.ExpiresAt) {
return domain.User{}, unauthorized()
}
user, exists, err := u.repository.User(ctx, session.UserID)
if err != nil {
return domain.User{}, err
}
if !exists {
return domain.User{}, unauthorized()
}
return user, nil
}
func (u *UseCase) CreateSession(ctx context.Context, username, secret string) (domain.Login, error) {
if !validUsername(username) || !validPassword(secret) {
return domain.Login{}, unauthorized()
}
user, hash, exists, err := u.repository.UserByUsername(ctx, username)
if err != nil {
return domain.Login{}, err
}
if !exists {
hash = password.DummyHash
}
valid, err := password.Verify(ctx, secret, hash)
if err != nil {
return domain.Login{}, err
}
if !valid || !exists {
return domain.Login{}, unauthorized()
}
var raw [32]byte
if _, err = rand.Read(raw[:]); err != nil {
return domain.Login{}, err
}
token := base64.RawURLEncoding.EncodeToString(raw[:])
expires := time.Now().UTC().Add(u.sessionTTL)
if err = u.sessions.Put(ctx, tokenKey(token), domain.Session{UserID: user.ID, ExpiresAt: expires}); err != nil {
return domain.Login{}, err
}
return domain.Login{Token: token, ExpiresAt: expires, User: user}, nil
}
func (u *UseCase) DeleteSession(ctx context.Context, token string) error {
deleted, err := u.sessions.Delete(ctx, tokenKey(token))
if err != nil {
return err
}
if !deleted {
return unauthorized()
}
return nil
}
func (u *UseCase) Ready(ctx context.Context) error {
if err := u.repository.Ready(ctx); err != nil {
return err
}
return u.sessions.Ready(ctx)
}
+19
View File
@@ -0,0 +1,19 @@
package chat
import (
"strings"
"testing"
)
func TestPasswordContract(t *testing.T) {
for _, value := range []string{"", "too-short", strings.Repeat(" ", 12), strings.Repeat("x", 129), strings.Repeat("x", 12) + string([]byte{0xff})} {
if validPassword(value) {
t.Fatal("invalid password accepted")
}
}
for _, value := range []string{strings.Repeat("🔑", 128), "valid:password", " password with spaces "} {
if !validPassword(value) {
t.Fatal("valid Unicode password rejected")
}
}
}
+37
View File
@@ -0,0 +1,37 @@
package chat
import (
"strings"
"unicode/utf8"
"github.com/google/uuid"
)
func normalizeUUID(value string) (string, bool) {
parsed, err := uuid.Parse(value)
if err != nil {
return "", false
}
normalized := parsed.String()
if !strings.EqualFold(value, normalized) {
return "", false
}
return normalized, true
}
func validUsername(value string) bool {
if len(value) < 3 || len(value) > 32 {
return false
}
for _, char := range value {
if char != '_' && (char < 'a' || char > 'z') && (char < '0' || char > '9') {
return false
}
}
return true
}
func validRequiredText(value string, maxRunes int) bool {
length := utf8.RuneCountInString(value)
return utf8.ValidString(value) && length >= 1 && length <= maxRunes && strings.TrimSpace(value) != ""
}
+54
View File
@@ -0,0 +1,54 @@
-- +goose Up
-- +goose StatementBegin
DO $$
BEGIN
-- Adopt the schema created by the previous runner without changing its data.
IF to_regclass('schema_migrations') IS NOT NULL THEN
IF NOT EXISTS (SELECT 1 FROM schema_migrations WHERE version = '001_initial.sql')
OR to_regclass('users') IS NULL OR to_regclass('chats') IS NULL
OR to_regclass('chat_members') IS NULL OR to_regclass('messages') IS NULL THEN
RAISE EXCEPTION 'incomplete legacy schema: cannot adopt migration 1';
END IF;
RETURN;
END IF;
CREATE TABLE users (
id uuid PRIMARY KEY,
username text NOT NULL UNIQUE CHECK (username ~ '^[a-z0-9_]{3,32}$'),
display_name text NOT NULL CHECK (char_length(display_name) BETWEEN 1 AND 100),
password_hash text NOT NULL,
created_at timestamptz NOT NULL DEFAULT clock_timestamp()
);
CREATE TABLE chats (
id uuid PRIMARY KEY,
title text NOT NULL CHECK (char_length(title) BETWEEN 1 AND 100),
created_at timestamptz NOT NULL DEFAULT clock_timestamp()
);
CREATE INDEX chats_history_idx ON chats (created_at, id);
CREATE TABLE chat_members (
chat_id uuid NOT NULL REFERENCES chats(id),
user_id uuid NOT NULL REFERENCES users(id),
ordinal integer NOT NULL CHECK (ordinal >= 0),
PRIMARY KEY (chat_id, user_id),
UNIQUE (chat_id, ordinal)
);
CREATE INDEX chat_members_user_idx ON chat_members (user_id, chat_id);
CREATE TABLE messages (
id uuid PRIMARY KEY,
chat_id uuid NOT NULL,
sender_id uuid NOT NULL,
text text NOT NULL CHECK (char_length(text) BETWEEN 1 AND 4000),
created_at timestamptz NOT NULL DEFAULT clock_timestamp(),
FOREIGN KEY (chat_id, sender_id) REFERENCES chat_members(chat_id, user_id)
);
CREATE INDEX messages_history_idx ON messages (chat_id, created_at, id);
END;
$$;
-- +goose StatementEnd
-- +goose Down
DROP TABLE messages;
DROP TABLE chat_members;
DROP TABLE chats;
DROP TABLE users;
-- The old journal must not claim that the dropped schema is still applied.
DROP TABLE IF EXISTS schema_migrations;
+15
View File
@@ -0,0 +1,15 @@
#!/bin/sh
set -eu
cd "$(dirname "$0")/.."
umask 077
mkdir -p secrets
chmod 700 secrets
for name in postgres_password cursor_key; do
if [ ! -s "secrets/$name" ]; then
openssl rand -hex 32 > "secrets/$name"
fi
done
# Compose mounts files directly on Linux; the unprivileged API must read them.
# The host directory remains private (0700).
chmod 444 secrets/postgres_password secrets/cursor_key
printf '%s\n' 'Local secrets are ready.'
+7
View File
@@ -0,0 +1,7 @@
#!/bin/sh
set -eu
cd "$(dirname "$0")/.."
if docker compose version >/dev/null 2>&1; then
exec docker compose --env-file /dev/null -f compose.yaml "$@"
fi
exec docker-compose --env-file /dev/null -f compose.yaml "$@"
+50
View File
@@ -0,0 +1,50 @@
#!/usr/bin/env python3
"""Reproducible local benchmark with resource samples; no credentials in output."""
import argparse
import json
import os
from pathlib import Path
import subprocess
import sys
import time
ROOT = Path(__file__).resolve().parents[1]
COMPOSE = str(ROOT / 'scripts/compose.sh')
def counts():
sql = 'SELECT json_build_object(\'users\',(SELECT count(*) FROM users),\'chats\',(SELECT count(*) FROM chats),\'messages\',(SELECT count(*) FROM messages))'
return json.loads(subprocess.check_output([COMPOSE, 'exec', '-T', 'postgres', 'psql', '-U', 'messenger', '-d', 'messenger', '-Atc', sql], text=True))
def main():
parser = argparse.ArgumentParser()
parser.add_argument('--base-url', default=os.environ.get('BASE_URL', 'http://localhost:8080'))
parser.add_argument('--duration', type=int, default=30)
parser.add_argument('--concurrency', type=int, default=4)
args = parser.parse_args()
command = [sys.executable, str(ROOT / 'tests/load.py'), '--base-url', args.base_url, '--concurrency', str(args.concurrency)]
subprocess.run(command + ['--duration', '3'], check=True, stdout=subprocess.DEVNULL)
before = counts()
ids = subprocess.check_output([COMPOSE, 'ps', '-q', 'api', 'postgres', 'redis'], text=True).split()
samples = []
process = subprocess.Popen(command + ['--duration', str(args.duration), '--output', str(ROOT / 'evidence/load.json')], stdout=subprocess.DEVNULL)
try:
while process.poll() is None:
stats = subprocess.check_output(['docker', 'stats', '--no-stream', '--format', '{{json .}}', *ids], text=True)
samples.append({'elapsed_sample': len(samples), 'containers': [json.loads(line) for line in stats.splitlines()]})
time.sleep(1)
finally:
if process.poll() is None:
process.terminate()
code = process.wait()
if code:
raise SystemExit(code)
report = {'warmup_seconds': 3, 'dataset_before': before, 'dataset_after': counts(), 'samples': samples}
(ROOT / 'evidence/resources.json').write_text(json.dumps(report, indent=2) + '\n')
print((ROOT / 'evidence/load.json').read_text())
print('Resource samples and dataset counts: evidence/resources.json')
if __name__ == '__main__':
main()
+6
View File
@@ -0,0 +1,6 @@
#!/bin/sh
set -eu
cd "$(dirname "$0")/.."
# Stop ALL running application dependencies; retain both named volumes.
./scripts/compose.sh stop api redis postgres
./scripts/compose.sh up -d --wait postgres redis api
+31
View File
@@ -0,0 +1,31 @@
# Собственные проверки lab2
Публичные `tests/*.py` оставлены без изменений.
- `make test-own`: Go race tests HTTP/use case и KDF; интеграционный тест пропускается
без INTEGRATION_TESTS=1.
- `make test-integration PORT=8080`: контейнер Go с race detector. Тест PostgreSQL
создаёт отдельную случайную схему и удаляет только её при завершении. Проверяет
goose up с нуля и повторно, переход со старого журнала с сохранением данных,
down/up в изолированной схеме, 12 конкурентных регистраций, rollback после вставки первого
участника, обход 10 000 сообщений с совпадающими timestamps; печатает EXPLAIN
(ANALYZE, BUFFERS) для страницы около 9000-го сообщения.
- `make test-grade4 PORT=8080`: HTTP-сценарий на работающем Compose-стенде. Создаёт
синтетические данные, проверяет неверный пароль, Bearer-only, logout, Unicode,
гонку 8 регистраций, реальные остановки Redis/PostgreSQL, восстановление сессии,
cursor после рестарта и expiry с SESSION_TTL_SECONDS=2. В finally восстанавливает
зависимости и обычный TTL=3600. Не запускайте параллельно smoke или нагрузке.
- `make test-persistence PORT=8080 ACTION_SCRIPT=scripts/restart.sh`: публичная
проверка полного рестарта с сохранением данных и прежнего токена.
Все Compose-команды относятся к проекту mtusi2026lab2. Токены и пароли живут только
в памяти теста, в результаты не выводятся. EXPLAIN использует синтетическую схему;
его время — измерение одного небольшого набора, не универсальная оценка PostgreSQL.
`make measure-load PORT=8080` выполняет 3 секунды прогрева и 30 секунд нагрузки
с конкуренцией 4; сохраняет latency/RPS/error ratio в `evidence/load.json`,
Docker stats и размеры набора данных в `evidence/resources.json`.
Для запуска интеграционных Go-тестов вне контейнера нужен `goose` v3.27.1 в PATH.
Контейнер tests уже содержит эту версию. Каталог SQL задаётся GOOSE_MIGRATION_DIR;
тест передаёт отдельный search_path и выполняет down только в своей временной схеме.
+120
View File
@@ -0,0 +1,120 @@
#!/usr/bin/env python3
"""Additional lab2 acceptance checks. Never print credentials or session tokens."""
import base64
from concurrent.futures import ThreadPoolExecutor
import os
from pathlib import Path
import subprocess
import sys
import time
import uuid
sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
from client import Client, Failure, check, run
ROOT = Path(__file__).resolve().parents[2]
def compose(*args, ttl=None):
env = dict(os.environ)
if ttl is not None:
env['SESSION_TTL_SECONDS'] = str(ttl)
result = subprocess.run([str(ROOT / 'scripts/compose.sh'), *args], env=env,
stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, timeout=180)
check(result.returncode == 0, 'compose operation failed: ' + args[0])
def login(c, username, password, expected=201):
basic = base64.b64encode((username + ':' + password).encode()).decode()
return c.call('POST', '/api/v1/auth/sessions', expected,
headers={'Authorization': 'Basic ' + basic}, schema='Session' if expected == 201 else None)
def main():
c = Client(timeout=5)
alice, bob, eve, chat = c.bootstrap()
credentials = alice['registration']
login(c, credentials['username'], 'incorrect-password', 401)
login(c, 'unknown_' + uuid.uuid4().hex[:12], 'incorrect-password', 401)
c.call('GET', '/api/v1/users/me', 401, headers={'X-User-Id': alice['id']})
basic = base64.b64encode((credentials['username'] + ':' + credentials['password']).encode()).decode()
c.call('GET', '/api/v1/users/me', 401, headers={'Authorization': 'Basic ' + basic})
response = c.call('GET', '/api/v1/users/me', actor=alice, headers={'X-User-Id': bob['id']}, schema='User')
check(response['json']['id'] == alice['id'], 'X-User-Id changed session owner')
c.call('DELETE', '/api/v1/auth/sessions/current', 204, actor=alice)
c.call('GET', '/api/v1/users/me', 401, actor=alice)
c.call('DELETE', '/api/v1/auth/sessions/current', 401, actor=alice)
print('PASS: wrong password, unknown user, Bearer-only access, X-User-Id ignored, logout')
# Maximum UTF-8 password length and a colon are supported without truncation.
username = 'unicode_' + uuid.uuid4().hex[:12]
password = '🔑' * 127 + ':'
c.call('POST', '/api/v1/users', 201, body={'username': username, 'display_name': 'Unicode', 'password': password}, schema='User')
login(c, username, password)
login(c, username, '🔑' * 127 + 'x', 401)
print('PASS: 128-code-point Unicode password including colon; suffix verified')
username = 'race_' + uuid.uuid4().hex[:12]
def register(_):
return Client().call('POST', '/api/v1/users', [201, 409], body={
'username': username, 'display_name': 'Concurrent', 'password': 'synthetic-password-123'
})['status']
with ThreadPoolExecutor(max_workers=8) as pool:
statuses = list(pool.map(register, range(8)))
check(statuses.count(201) == 1 and statuses.count(409) == 7, 'registration race broken')
print('PASS: HTTP registration race: one 201, seven 409')
# Revoke before restart: absence must also survive AOF recovery.
for service in ('redis', 'postgres'):
compose('stop', service)
try:
c.call('GET', '/health/live', schema='Health')
start = time.monotonic()
c.call('GET', '/health/ready', 503)
check(time.monotonic() - start < 4, 'readiness error exceeded timeout budget')
c.call('GET', '/api/v1/users/me', 503, actor=bob)
c.call('GET', '/api/v1/users/me', 401, headers={'X-User-Id': bob['id']})
login(c, bob['registration']['username'], bob['registration']['password'], 503)
c.call('POST', '/api/v1/chats/' + chat['id'] + '/messages', 503, actor=bob, body={'text': 'must fail'})
finally:
compose('up', '-d', '--wait', service)
c.call('GET', '/health/ready', schema='Health')
c.call('GET', '/api/v1/users/me', actor=bob, schema='User')
c.call('GET', '/api/v1/users/me', 401, actor=alice)
print('PASS: ' + service + ' outage bounded; live=200, ready=503, protected=503, anonymous=401; session recovered, logout retained')
# The same signed cursor remains valid across an API process restart.
c.message(bob, chat, 'cursor before restart 1')
c.message(bob, chat, 'cursor before restart 2')
page = c.call('GET', '/api/v1/chats/' + chat['id'] + '/messages?limit=1', actor=bob, schema='MessagePage')['json']
check(page['next_cursor'] is not None, 'missing cursor')
compose('restart', 'api')
deadline = time.monotonic() + 30
while True:
try:
c.call('GET', '/health/ready', schema='Health')
break
except Failure:
check(time.monotonic() < deadline, 'API did not recover')
time.sleep(.2)
from urllib.parse import quote
c.call('GET', '/api/v1/chats/' + chat['id'] + '/messages?cursor=' + quote(page['next_cursor']), actor=bob, schema='MessagePage')
print('PASS: cursor and existing session survive API restart')
try:
compose('up', '-d', '--wait', '--force-recreate', 'api', ttl=2)
short = c.user('expiry')
c.call('GET', '/api/v1/users/me', actor=short, schema='User')
time.sleep(2.2)
c.call('GET', '/api/v1/users/me', 401, actor=short)
compose('restart', 'redis')
compose('up', '-d', '--wait', 'redis')
c.call('GET', '/api/v1/users/me', 401, actor=short)
print('PASS: SESSION_TTL_SECONDS=2 expires; Redis restart does not revive expired session')
finally:
compose('up', '-d', '--wait', '--force-recreate', 'api', ttl=3600)
print('PASS: all grade-4 HTTP checks; normal TTL restored to 3600')
if __name__ == '__main__':
run(main)