forked from mtusi2026/mtusi2026lab2
Compare commits
10
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
15492d7894 | ||
|
|
c8470beeee | ||
|
|
a288193cda | ||
|
|
d25054843c | ||
|
|
af88065a1c | ||
|
|
9ec1eae7b8 | ||
|
|
f86d79a584 | ||
|
|
497f677453 | ||
|
|
0e62ba9660 | ||
|
|
fff2cb5b37 |
@@ -1,37 +1,152 @@
|
|||||||
# Отчёт — лабораторная 2
|
# Отчёт — лабораторная 2
|
||||||
|
|
||||||
- Автор, группа: TODO
|
- Автор, группа: Каменски Лин, БПИ2301
|
||||||
- Целевая оценка; выбранный трек 5, если нужен: TODO
|
- Целевая оценка; выбранный трек 5, если нужен: 5; трек 2
|
||||||
- Commit/PR: TODO после публикации
|
- Commit/PR: [Pull Request 20](https://gitea.privcloud.tech/mtusi2026/mtusi2026lab2/pulls/20)
|
||||||
- Использованные источники, библиотеки и помощь ИИ: TODO
|
- Использованные источники, библиотеки и помощь ИИ: материалы лабораторной; Go, chi, pgx v5, sqlc, goose, PostgreSQL 18.6, Redis 8.8.3; Claude, ChatGPT - для ускорения работы и оформления отчёта
|
||||||
|
|
||||||
## Запуск из чистого clone
|
## Запуск из чистого clone
|
||||||
|
|
||||||
TODO: версии runtime/образов, prerequisites, команды создания локальных secrets/.env, build, миграций, запуска, ожидания готовности, тестов и остановки. Указать необходимые действия оператора. Не вставлять секреты. Отдельно указать безопасную остановку и команду намеренного удаления учебных данных.
|
Требуются Go 1.26+ и Docker с Compose. Образы: PostgreSQL 18.6, Redis 8.8.3.
|
||||||
|
|
||||||
|
Создать локальные secrets - файлы в `secrets/`, в каждый записать значение без лишних символов:
|
||||||
|
- `database_url.txt` - URL PostgreSQL для API;
|
||||||
|
- `cache_url.txt` - URL Redis;
|
||||||
|
- `postgres_password.txt` - пароль пользователя `messenger`;
|
||||||
|
- `test_database_url.txt` - URL БД для тестов.
|
||||||
|
|
||||||
|
Пример (значения заменить своими):
|
||||||
|
```bash
|
||||||
|
mkdir -p secrets
|
||||||
|
printf '%s' 'CHANGE_ME' > secrets/postgres_password.txt
|
||||||
|
printf '%s' 'postgres://messenger:CHANGE_ME@postgres:5432/messenger?sslmode=disable' > secrets/database_url.txt
|
||||||
|
printf '%s' 'redis://redis:6379/0' > secrets/cache_url.txt
|
||||||
|
printf '%s' 'postgres://messenger:CHANGE_ME@127.0.0.1:5432/messenger?sslmode=disable' > secrets/test_database_url.txt
|
||||||
|
```
|
||||||
|
|
||||||
|
Скопировать шаблон переменных окружения:
|
||||||
|
```bash
|
||||||
|
cp .env.example .env
|
||||||
|
```
|
||||||
|
|
||||||
|
Сборка и запуск (сервис `migrate` применяет миграции goose автоматически):
|
||||||
|
```bash
|
||||||
|
docker compose up --build -d
|
||||||
|
```
|
||||||
|
|
||||||
|
Готовность API проверяется запросом к `/health/ready`; после этого API доступен на http://localhost:8080.
|
||||||
|
|
||||||
|
Тесты:
|
||||||
|
```bash
|
||||||
|
make test
|
||||||
|
make test-persistence ACTION_SCRIPT=scripts/restart.sh
|
||||||
|
make contract-go
|
||||||
|
make race-go
|
||||||
|
make failure-go
|
||||||
|
```
|
||||||
|
|
||||||
|
Безопасная остановка (данные в volume `pgdata` сохраняются):
|
||||||
|
```bash
|
||||||
|
docker compose down
|
||||||
|
```
|
||||||
|
|
||||||
|
Намеренное удаление учебных данных:
|
||||||
|
```bash
|
||||||
|
docker compose down -v
|
||||||
|
```
|
||||||
|
|
||||||
## Архитектура и решения
|
## Архитектура и решения
|
||||||
|
|
||||||
TODO: схема процессов/хранилищ, источник истины, транзакционные границы, ограничения. Что перенесено из lab1, что изменено в этой работе. Соответствие переменных из .env.example реальной конфигурации.
|
Процессы/хранилища: `api` (Go), `postgres`, `redis`, одноразовый `migrate` (goose). Источник истины - PostgreSQL. Redis хранит только кэш сессий: TTL записи = min(60 с, оставшийся срок сессии до `expires_at`); при logout запись удаляется сначала из PostgreSQL, затем из Redis. При недоступности Redis API обходит кэш и читает сессию из PostgreSQL; при недоступности PostgreSQL API отвечает `503`. Создание чата выполняется в одной транзакции (откат проверяется `TestCreateChatRollback`).
|
||||||
|
|
||||||
|
Пароли хешируются bcrypt; перед этим пароль проходит через SHA-256, чтобы обойти ограничение bcrypt в 72 байта.
|
||||||
|
|
||||||
|
Из lab1 перенесены слои `handler` (HTTP) и `service` (бизнес-логика). Хранилище в памяти (`store`) заменено кодом доступа к PostgreSQL (sqlc, pgxpool) и удалено; `X-User-Id` заменён на Bearer-сессии.
|
||||||
|
|
||||||
|
Переменные `.env.example`: `APP_HOST`, `APP_PORT` - адрес и порт API; `MAX_INFLIGHT_REQUESTS` - ограничитель запросов из lab1 (0 - выключен); `SESSION_TTL_SECONDS` - срок жизни сессии; `LOG_LEVEL` - уровень логов; `DATABASE_URL_FILE`, `CACHE_URL_FILE` - пути к secrets с URL PostgreSQL и Redis.
|
||||||
|
|
||||||
## Доказательства критериев
|
## Доказательства критериев
|
||||||
|
|
||||||
| Критерий README | Команда/сценарий | Наблюдаемый результат | Файл доказательства |
|
| Критерий README | Команда/сценарий | Наблюдаемый результат | Файл доказательства |
|
||||||
| --- | --- | --- | --- |
|
| --- | --- | --- | --- |
|
||||||
| Публичный smoke | make test | TODO | TODO |
|
| Публичный smoke | `make test` | `PASS` | `evidence/make-test.txt` |
|
||||||
| Остальные пункты уровня 3 | TODO | TODO | TODO |
|
| Уровень 3 |
|
||||||
| Все пункты уровня 4, если заявлен | TODO | TODO | TODO |
|
| Сохранность данных и сессии после рестарта | `make test-persistence ACTION_SCRIPT=scripts/restart.sh`; скрипт выполняет `docker compose restart postgres redis api`, volumes сохраняются | `PASS`: данные и существующая сессия сохранены | `evidence/make-test-persistence.txt` |
|
||||||
| Выбранный трек 5, если заявлен | TODO | TODO | TODO |
|
| Повторный запуск миграций без дублирования данных | повторный запуск сервиса `migrate` | `no migrations to run` | `evidence/migrate-repeat.txt` |
|
||||||
|
| Уникальность username | `make contract-go` (`TestDuplicateUsername`) | `PASS` | `evidence/make-contract-go.txt` |
|
||||||
TODO: добавить отдельную строку для каждого заявленного критерия. PASS без команды и наблюдения не является доказательством. Проверка инфраструктурного hook требует подтверждения, какие реальные процессы/хранилища перезапущены.
|
| Срок жизни сессии | `make failure-go` (`TestSessionExpiry`) | `PASS` | `evidence/make-failure-go.txt` |
|
||||||
|
| Уровень 4 |
|
||||||
|
| Гонка регистрации одного username | `make race-go` (`TestConcurrentRegistration`) | `PASS` | `evidence/make-race-go.txt` |
|
||||||
|
| Rollback составной операции | `make contract-go` (`TestCreateChatRollback`) | `PASS` | `evidence/make-contract-go.txt` |
|
||||||
|
| Индекс истории, пагинация без полного scan | `EXPLAIN (ANALYZE, BUFFERS)`, 20 000 сообщений | Seq Scan + Sort 5,2 мс, 507 буферов → Index Scan 0,03 мс, 4 буфера | `evidence/explain-history.txt` |
|
||||||
|
| Logout, неверный пароль | `make contract-go` (`TestLogout`, `TestLoginWrongPassword`) | `PASS` | `evidence/make-contract-go.txt` |
|
||||||
|
| Недоступность Redis и БД | `make failure-go` (`TestRedisDown`, `TestDatabaseDown`) | `PASS` | `evidence/make-failure-go.txt` |
|
||||||
|
| Уровень 5 |
|
||||||
|
| Трек 2: стоимость записи | вставка 100 000 сообщений (чаты 60 000 / 5×5 000 / 200×75) для вариантов A, B, C | B и C медленнее A; дополнительные индексы занимают 4880–5776 КБ | `evidence/track2-insert-cost.txt` |
|
||||||
|
| Трек 2: план запроса | `EXPLAIN (ANALYZE, BUFFERS)` для A, B, C на чатах `big` и `small-1` | A: Seq Scan, 2264 буфера; B: Index Scan, 8-9 буферов; C: Index Scan + Sort, 1730 буферов на `big` | `evidence/track2-explain.txt` |
|
||||||
|
| Трек 2: backup → restore | `pg_dump -Fc` → `pg_restore` в `research_restore` | `count` = 100 000, хеш таблицы и хеш выбранной страницы совпали | `evidence/track2-backup-restore.txt` |
|
||||||
|
|
||||||
## Эксперименты и отказы
|
## Эксперименты и отказы
|
||||||
|
|
||||||
TODO: гипотеза, hardware/лимиты, версии, объём данных, профиль нагрузки, concurrency/arrival rate, длительность/прогрев, повторы, успешные RPS, ошибки, p50/p95/p99, CPU/RAM. Сохранить raw summary без tokens и объяснить ограничения измерения.
|
Для сравнения использовались три варианта индексации таблицы `messages`:
|
||||||
|
- A - только первичный ключ `(PK)`, без дополнительного индекса;
|
||||||
|
- B - индекс `(chat_id, created_at, id)`;
|
||||||
|
- C - индекс `(chat_id, id)`.
|
||||||
|
|
||||||
|
Для каждого варианта выполнялись эксперименты с записью и чтением. Дополнительно проверялись резервное копирование и восстановление данных.
|
||||||
|
|
||||||
|
**Гипотезы**:
|
||||||
|
1. Индекс `(chat_id, created_at, id)` (B) позволит получить страницу из 50 сообщений за сопоставимое время и с сопоставимым числом обращений к данным в малом и большом чате;
|
||||||
|
2. Индекс `(chat_id, id)` (C) хуже индекса `(chat_id, created_at, id)` (B), поскольку может потребоваться дополнительная сортировка по `created_at, id`;
|
||||||
|
3. Каждый индекс замедляет вставку и занимает место.
|
||||||
|
|
||||||
|
**Методика**:
|
||||||
|
|
||||||
|
Эксперимент проводился в Docker Desktop с доступными 12 ядрами процессора и примерно 7,7 ГБ оперативной памяти. PostgreSQL 18.6, отдельная БД `research`, 100 000 сообщений: 1 чат на 60 000, 5 по 5 000, 200 по 75. Данные синтетические, сгенерированы один раз во вспомогательной таблице `messages_seed`.
|
||||||
|
|
||||||
|
Запись: для каждого варианта выполнено по 3 измерения времени вставки 100 000 одинаковых строк; перед каждым измерением таблица очищалась через TRUNCATE. Для вариантов B и C индекс создавался до начала измерений.
|
||||||
|
|
||||||
|
Чтение: для каждого варианта выполнено чтение страницы из 50 сообщений после курсора из середины истории, `EXPLAIN (ANALYZE, BUFFERS)`, чаты `big` и `small-1`, 2 измерения (каждый запрос выполнялся дважды, в таблице приведено второе измерение, когда данные уже в кэше).
|
||||||
|
|
||||||
|
Backup сделан при индексе B. Проверка: `count(*)`, `md5` по всем строкам таблицы и `md5` по странице из 50 сообщений чата `big` (тот же курсор, что в `EXPLAIN`); значения хэша в `research` и `research_restore` совпали.
|
||||||
|
|
||||||
|
Выполненные команды видны в выводе сессий psql в `evidence/track2-*.txt`.
|
||||||
|
|
||||||
|
**Результаты экспериментов**:
|
||||||
|
|
||||||
|
Запись:
|
||||||
|
|
||||||
|
| Вариант | Измерения, мс | Размер PK/индексов, КБ |
|
||||||
|
| --- | --- | --- |
|
||||||
|
| A | 990, 977, 978 | 3104 |
|
||||||
|
| B | 1655, 1640, 1157 | 8880 |
|
||||||
|
| C | 1223, 1181, 1185 | 7984 |
|
||||||
|
|
||||||
|
Чтение:
|
||||||
|
|
||||||
|
| Вариант | `big` (60 000) | `small-1` (75) |
|
||||||
|
| --- | --- | --- |
|
||||||
|
| A | 2264 / 10,3 мс | 2264 / 6,2 мс |
|
||||||
|
| B | 8 / 0,06 мс | 9 / 0,10 мс |
|
||||||
|
| C | 1730 / 13,6 мс | 10 / 0,17 мс |
|
||||||
|
|
||||||
| Воздействие | Что ожидаем | Что наблюдали | Время восстановления / потеря данных |
|
| Воздействие | Что ожидаем | Что наблюдали | Время восстановления / потеря данных |
|
||||||
| --- | --- | --- | --- |
|
| --- | --- | --- | --- |
|
||||||
| TODO | TODO | TODO | TODO |
|
| Вставка 100 000 сообщений без индекса (A) | минимальная стоимость записи | 977–990 мс | - |
|
||||||
|
| Вставка 100 000 сообщений с индексом `(chat_id, created_at, id)` (B) | вставка медленнее | 1157–1655 мс; индекс 5776 КБ | - |
|
||||||
|
| Вставка 100 000 сообщений с индексом `(chat_id, id)` (C) | вставка медленнее | 1181–1223 мс; индекс 4880 КБ | - |
|
||||||
|
| Запрос страницы без индекса (A) | стоимость зависит от размера таблицы | `Seq Scan`, 2264 буфера | - |
|
||||||
|
| Запрос страницы с индексом `(chat_id, created_at, id)` (B) | стоимость слабо зависит от размера чата | `Index Scan`, 8–9 буферов, без `Sort` | - |
|
||||||
|
| Запрос страницы с индексом `(chat_id, id)` (C) | хуже B на большом чате | `Index Scan` + `Sort`, 1730 буферов на `big` | - |
|
||||||
|
| `pg_dump -Fc` → `pg_restore` | полное восстановление данных | 4,1 МБ; backup 0,69 с; restore 0,54 с; хэши совпали | 0,54 с; потеря - изменения после последнего backup |
|
||||||
|
|
||||||
|
**Вывод**: Гипотеза 1 подтверждена: с индексом B страница читается за 8-9 буферов и 0,06-0,10 мс и в большом, и в малом чате. Гипотеза 2 подтверждена: на большом чате с индексом C читается 1730 буферов за 13,6 мс против 8 буферов и 0,06 мс с индексом B, потому что условие курсора не входит в индекс и нужна сортировка. Гипотеза 3 подтверждена: оба индекса замедляют вставку (977-990 мс без индекса, 1157-1655 мс с B, 1181-1223 мс с C) и занимают место (дополнительно 5776 КБ у B и 4880 КБ у C). Backup и restore восстановили 100 000 сообщений без потери проверенных данных; для истории сообщений выбран индекс B.
|
||||||
|
|
||||||
## Ограничения и следующие шаги
|
## Ограничения и следующие шаги
|
||||||
|
|
||||||
TODO: какие отказы выдерживаются и какие нет; что не реализовано; где учебное упрощение; какое улучшение подтверждено, а какое пока гипотеза.
|
- Сервер и volume общие для `messenger`, `research` и `research_restore`: эксперимент подтверждает корректность дампа, но не сохранность данных при отказе диска, так как копия лежит на том же носителе.
|
||||||
|
- Данные синтетические; размеры индексов и степень сжатия дампа на реальных данных будут другими.
|
||||||
|
- Один курсор из середины истории; каждый запрос выполнялся дважды, в результатах приведён второй прогон при заполненном кэше.
|
||||||
|
- Время backup и restore включает накладные расходы `docker compose exec`; параллельной записи во время backup не было, консистентность дампа под нагрузкой не проверялась.
|
||||||
|
- Redis в backup не входит: это кэш, источник истины PostgreSQL.
|
||||||
|
- После logout при недоступном Redis токен может приниматься до истечения кэш-TTL (до 60 с).
|
||||||
|
|||||||
+18
-7
@@ -40,7 +40,7 @@ WHERE c.id = sqlc.arg(id)
|
|||||||
AND m.user_id = sqlc.arg(user_id)
|
AND m.user_id = sqlc.arg(user_id)
|
||||||
);
|
);
|
||||||
|
|
||||||
-- name: ListChats :many
|
-- name: ListChatsFirstPage :many
|
||||||
SELECT
|
SELECT
|
||||||
c.*,
|
c.*,
|
||||||
ARRAY(
|
ARRAY(
|
||||||
@@ -51,12 +51,23 @@ SELECT
|
|||||||
FROM chats c
|
FROM chats c
|
||||||
JOIN chat_members m ON m.chat_id = c.id
|
JOIN chat_members m ON m.chat_id = c.id
|
||||||
WHERE m.user_id = sqlc.arg(user_id)
|
WHERE m.user_id = sqlc.arg(user_id)
|
||||||
AND (
|
ORDER BY c.created_at, c.id
|
||||||
sqlc.narg(after_created_at)::timestamptz IS NULL
|
LIMIT sqlc.arg(lim);
|
||||||
OR (c.created_at, c.id) > (
|
|
||||||
sqlc.narg(after_created_at)::timestamptz,
|
-- name: ListChatsAfter :many
|
||||||
sqlc.narg(after_id)::uuid
|
SELECT
|
||||||
)
|
c.*,
|
||||||
|
ARRAY(
|
||||||
|
SELECT cm.user_id FROM chat_members cm
|
||||||
|
WHERE cm.chat_id = c.id
|
||||||
|
ORDER BY cm.user_id
|
||||||
|
)::uuid[] AS member_ids
|
||||||
|
FROM chats c
|
||||||
|
JOIN chat_members m ON m.chat_id = c.id
|
||||||
|
WHERE m.user_id = sqlc.arg(user_id)
|
||||||
|
AND (c.created_at, c.id) > (
|
||||||
|
sqlc.arg(after_created_at)::timestamptz,
|
||||||
|
sqlc.arg(after_id)::uuid
|
||||||
)
|
)
|
||||||
ORDER BY c.created_at, c.id
|
ORDER BY c.created_at, c.id
|
||||||
LIMIT sqlc.arg(lim);
|
LIMIT sqlc.arg(lim);
|
||||||
|
|||||||
+10
-7
@@ -17,15 +17,18 @@ WHERE EXISTS (
|
|||||||
)
|
)
|
||||||
RETURNING *;
|
RETURNING *;
|
||||||
|
|
||||||
-- name: ListMessages :many
|
-- name: ListMessagesFirstPage :many
|
||||||
SELECT * FROM messages
|
SELECT * FROM messages
|
||||||
WHERE chat_id = sqlc.arg(chat_id)
|
WHERE chat_id = sqlc.arg(chat_id)
|
||||||
AND (
|
ORDER BY created_at, id
|
||||||
sqlc.narg(after_created_at)::timestamptz IS NULL
|
LIMIT sqlc.arg(lim);
|
||||||
OR (created_at, id) > (
|
|
||||||
sqlc.narg(after_created_at)::timestamptz,
|
-- name: ListMessagesAfter :many
|
||||||
sqlc.narg(after_id)::uuid
|
SELECT * FROM messages
|
||||||
)
|
WHERE chat_id = sqlc.arg(chat_id)
|
||||||
|
AND (created_at, id) > (
|
||||||
|
sqlc.arg(after_created_at)::timestamptz,
|
||||||
|
sqlc.arg(after_id)::uuid
|
||||||
)
|
)
|
||||||
ORDER BY created_at, id
|
ORDER BY created_at, id
|
||||||
LIMIT sqlc.arg(lim);
|
LIMIT sqlc.arg(lim);
|
||||||
|
|||||||
@@ -9,8 +9,8 @@ INSERT INTO sessions (
|
|||||||
sqlc.arg(expires_at)
|
sqlc.arg(expires_at)
|
||||||
);
|
);
|
||||||
|
|
||||||
-- name: GetSessionUserID :one
|
-- name: GetActiveSession :one
|
||||||
SELECT user_id FROM sessions
|
SELECT user_id, expires_at FROM sessions
|
||||||
WHERE token_hash = sqlc.arg(token_hash)
|
WHERE token_hash = sqlc.arg(token_hash)
|
||||||
AND expires_at > now();
|
AND expires_at > now();
|
||||||
|
|
||||||
|
|||||||
Binary file not shown.
@@ -0,0 +1,9 @@
|
|||||||
|
> make failure-go
|
||||||
|
go test -tags=failure ./student-tests/... -v -args -base-url=http://localhost:8080
|
||||||
|
=== RUN TestRedisDown
|
||||||
|
--- PASS: TestRedisDown (2.12s)
|
||||||
|
=== RUN --- PASS: TestDatabaseDown (10.90s)
|
||||||
|
=== RUN TestSessionExpiry
|
||||||
|
--- PASS: TestSessionExpiry (5.77s)
|
||||||
|
PASS
|
||||||
|
ok mtusi2026-messenger/student-tests 18.803s
|
||||||
@@ -0,0 +1,9 @@
|
|||||||
|
> make race-go
|
||||||
|
go test -tags=race ./student-tests/... -race -v -args -base-url=http://localhost:8080
|
||||||
|
=== RUN TestConcurrentMessages
|
||||||
|
race_test.go:98: PASS: 10 concurrent clients sent 100 messages, exactly 100 unique messages persisted
|
||||||
|
--- PASS: TestConcurrentMessages (0.31s)
|
||||||
|
=== RUN TestConcurrentRegistration
|
||||||
|
--- PASS: TestConcurrentRegistration (0.12s)
|
||||||
|
PASS
|
||||||
|
ok mtusi2026-messenger/student-tests 1.443s
|
||||||
@@ -0,0 +1,4 @@
|
|||||||
|
> make test-persistence ACTION_SCRIPT=scripts/restart.sh
|
||||||
|
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.
|
||||||
@@ -0,0 +1,3 @@
|
|||||||
|
> make test
|
||||||
|
python3 tests/smoke.py --base-url "http://localhost:8080"
|
||||||
|
PASS: lab2 public API scenario; infrastructure and grading evidence remain separate.
|
||||||
@@ -0,0 +1,4 @@
|
|||||||
|
> docker compose run --rm --no-deps migrate
|
||||||
|
Container mtusi2026lab2-migrate-run-481a17e62bda Creating
|
||||||
|
Container mtusi2026lab2-migrate-run-481a17e62bda Created
|
||||||
|
2026/10/07 20:39:09 goose: no migrations to run. current version: 1
|
||||||
@@ -0,0 +1,70 @@
|
|||||||
|
research=# DROP TABLE messages_seed;
|
||||||
|
DROP TABLE
|
||||||
|
Time: 4.369 ms
|
||||||
|
research=# CREATE INDEX idx_messages_chat_history ON messages (chat_id, created_at, id);
|
||||||
|
CREATE INDEX
|
||||||
|
Time: 75.459 ms
|
||||||
|
research=# ANALYZE messages;
|
||||||
|
ANALYZE
|
||||||
|
Time: 92.896 ms
|
||||||
|
research=# SELECT count(*) FROM messages;
|
||||||
|
count
|
||||||
|
--------
|
||||||
|
100000
|
||||||
|
(1 row)
|
||||||
|
|
||||||
|
Time: 7.997 ms
|
||||||
|
research=# SELECT md5(string_agg(id::text || chat_id::text || created_at::text || text, '' ORDER BY id)) AS full_hash FROM messages;
|
||||||
|
full_hash
|
||||||
|
----------------------------------
|
||||||
|
3b0b6c7f0769218c3d3d1a7b660f521c
|
||||||
|
(1 row)
|
||||||
|
|
||||||
|
Time: 74.820 ms
|
||||||
|
research=# SELECT md5(string_agg(id::text || text, '' ORDER BY created_at, id)) AS page_hash FROM (SELECT * FROM messages WHERE chat_id = (SELECT id FROM chats WHERE title = 'big') AND (created_at, id) > ('2026-01-15 00:00+00', '00000000-0000-0000-0000-000000000000') ORDER BY created_at, id LIMIT 50) p;
|
||||||
|
page_hash
|
||||||
|
----------------------------------
|
||||||
|
1b111bf87f61b52ef916f31037c4acb5
|
||||||
|
(1 row)
|
||||||
|
|
||||||
|
Time: 0.736 ms
|
||||||
|
research=# \q
|
||||||
|
|
||||||
|
> Measure-Command { docker compose exec postgres pg_dump -U messenger -d research -Fc -f /tmp/research.dump } | Select-Object TotalSeconds
|
||||||
|
|
||||||
|
TotalSeconds
|
||||||
|
------------
|
||||||
|
0,6917214
|
||||||
|
> docker compose exec postgres psql -U messenger -d postgres -c "CREATE DATABASE research_restore;"
|
||||||
|
CREATE DATABASE
|
||||||
|
> Measure-Command { docker compose exec postgres pg_restore -U messenger -d research_restore /tmp/research.dump } | Select-Object TotalSeconds
|
||||||
|
|
||||||
|
TotalSeconds
|
||||||
|
------------
|
||||||
|
0,5392463
|
||||||
|
> docker compose exec postgres ls -lh /tmp/research.dump
|
||||||
|
-rw-r--r-- 1 root root 4.1M Oct 7 19:48 /tmp/research.dump
|
||||||
|
> docker compose exec postgres psql -U messenger -d research_restore
|
||||||
|
psql (18.6 (Debian 18.6-1.pgdg13+2))
|
||||||
|
Type "help" for help.
|
||||||
|
|
||||||
|
research_restore=# SELECT count(*) FROM messages;
|
||||||
|
count
|
||||||
|
--------
|
||||||
|
100000
|
||||||
|
(1 row)
|
||||||
|
|
||||||
|
research_restore=# SELECT md5(string_agg(id::text || chat_id::text || created_at::text || text, '' ORDER BY id)) AS full_hash FROM messages;
|
||||||
|
full_hash
|
||||||
|
----------------------------------
|
||||||
|
3b0b6c7f0769218c3d3d1a7b660f521c
|
||||||
|
(1 row)
|
||||||
|
|
||||||
|
research_restore=# SELECT md5(string_agg(id::text || text, '' ORDER BY created_at, id)) AS page_hash FROM (SELECT * FROM messages WHERE chat_id = (SELECT id FROM chats WHERE title = 'big') AND (created_at, id) > ('2026-01-15 00:00+00', '00000000-0000-0000-0000-000000000000') ORDER BY created_at, id LIMIT 50) p;
|
||||||
|
page_hash
|
||||||
|
----------------------------------
|
||||||
|
1b111bf87f61b52ef916f31037c4acb5
|
||||||
|
(1 row)
|
||||||
|
|
||||||
|
research_restore=# \q
|
||||||
|
> docker compose exec postgres rm /tmp/research.dump
|
||||||
@@ -0,0 +1,297 @@
|
|||||||
|
C. (chat_id, id)
|
||||||
|
research=# EXPLAIN (ANALYZE, BUFFERS) SELECT * FROM messages WHERE chat_id = (SELECT id FROM chats WHERE title = 'big') AND (created_at, id) > ('2026-01-15 00:00+00', '00000000-0000-0000-0000-000000000000') ORDER BY created_at, id LIMIT 50;
|
||||||
|
QUERY PLAN
|
||||||
|
--------------------------------------------------------------------------------------------------------------------------------------------------------
|
||||||
|
Limit (cost=810.77..810.89 rows=50 width=151) (actual time=11.161..11.167 rows=50.00 loops=1)
|
||||||
|
Buffers: shared hit=1730
|
||||||
|
InitPlan 1
|
||||||
|
-> Seq Scan on chats (cost=0.00..4.58 rows=1 width=16) (actual time=0.012..0.024 rows=1.00 loops=1)
|
||||||
|
Filter: (title = 'big'::text)
|
||||||
|
Rows Removed by Filter: 205
|
||||||
|
Buffers: shared hit=2
|
||||||
|
-> Sort (cost=806.19..806.68 rows=193 width=151) (actual time=11.159..11.162 rows=50.00 loops=1)
|
||||||
|
Sort Key: messages.created_at, messages.id
|
||||||
|
Sort Method: top-N heapsort Memory: 36kB
|
||||||
|
Buffers: shared hit=1730
|
||||||
|
-> Index Scan using idx_messages_chat_id on messages (cost=0.42..799.78 rows=193 width=151) (actual time=2.648..8.533 rows=39841.00 loops=1)
|
||||||
|
Index Cond: (chat_id = (InitPlan 1).col1)
|
||||||
|
Filter: (ROW(created_at, id) > ROW('2026-01-15 00:00:00+00'::timestamp with time zone, '00000000-0000-0000-0000-000000000000'::uuid))
|
||||||
|
Rows Removed by Filter: 20159
|
||||||
|
Index Searches: 1
|
||||||
|
Buffers: shared hit=1730
|
||||||
|
Planning Time: 0.115 ms
|
||||||
|
Execution Time: 11.189 ms
|
||||||
|
(19 rows)
|
||||||
|
|
||||||
|
Time: 11.614 ms
|
||||||
|
research=# EXPLAIN (ANALYZE, BUFFERS) SELECT * FROM messages WHERE chat_id = (SELECT id FROM chats WHERE title = 'big') AND (created_at, id) > ('2026-01-15 00:00+00', '00000000-0000-0000-0000-000000000000') ORDER BY created_at, id LIMIT 50;
|
||||||
|
QUERY PLAN
|
||||||
|
---------------------------------------------------------------------------------------------------------------------------------------------------------
|
||||||
|
Limit (cost=810.77..810.89 rows=50 width=151) (actual time=13.602..13.609 rows=50.00 loops=1)
|
||||||
|
Buffers: shared hit=1730
|
||||||
|
InitPlan 1
|
||||||
|
-> Seq Scan on chats (cost=0.00..4.58 rows=1 width=16) (actual time=0.034..0.044 rows=1.00 loops=1)
|
||||||
|
Filter: (title = 'big'::text)
|
||||||
|
Rows Removed by Filter: 205
|
||||||
|
Buffers: shared hit=2
|
||||||
|
-> Sort (cost=806.19..806.68 rows=193 width=151) (actual time=13.601..13.604 rows=50.00 loops=1)
|
||||||
|
Sort Key: messages.created_at, messages.id
|
||||||
|
Sort Method: top-N heapsort Memory: 36kB
|
||||||
|
Buffers: shared hit=1730
|
||||||
|
-> Index Scan using idx_messages_chat_id on messages (cost=0.42..799.78 rows=193 width=151) (actual time=3.012..10.954 rows=39841.00 loops=1)
|
||||||
|
Index Cond: (chat_id = (InitPlan 1).col1)
|
||||||
|
Filter: (ROW(created_at, id) > ROW('2026-01-15 00:00:00+00'::timestamp with time zone, '00000000-0000-0000-0000-000000000000'::uuid))
|
||||||
|
Rows Removed by Filter: 20159
|
||||||
|
Index Searches: 1
|
||||||
|
Buffers: shared hit=1730
|
||||||
|
Planning Time: 0.207 ms
|
||||||
|
Execution Time: 13.645 ms
|
||||||
|
(19 rows)
|
||||||
|
|
||||||
|
Time: 14.423 ms
|
||||||
|
research=# EXPLAIN (ANALYZE, BUFFERS) SELECT * FROM messages WHERE chat_id = (SELECT id FROM chats WHERE title = 'small-1') AND (created_at, id) > ('2026-01-01 00:30+00', '00000000-0000-0000-0000-000000000000') ORDER BY created_at, id LIMIT 50;
|
||||||
|
QUERY PLAN
|
||||||
|
-----------------------------------------------------------------------------------------------------------------------------------------------------
|
||||||
|
Limit (cost=819.50..819.63 rows=50 width=151) (actual time=0.140..0.148 rows=46.00 loops=1)
|
||||||
|
Buffers: shared hit=10
|
||||||
|
InitPlan 1
|
||||||
|
-> Seq Scan on chats (cost=0.00..4.58 rows=1 width=16) (actual time=0.011..0.020 rows=1.00 loops=1)
|
||||||
|
Filter: (title = 'small-1'::text)
|
||||||
|
Rows Removed by Filter: 205
|
||||||
|
Buffers: shared hit=2
|
||||||
|
-> Sort (cost=814.93..816.07 rows=456 width=151) (actual time=0.139..0.142 rows=46.00 loops=1)
|
||||||
|
Sort Key: messages.created_at, messages.id
|
||||||
|
Sort Method: quicksort Memory: 35kB
|
||||||
|
Buffers: shared hit=10
|
||||||
|
-> Index Scan using idx_messages_chat_id on messages (cost=0.42..799.78 rows=456 width=151) (actual time=0.039..0.047 rows=46.00 loops=1)
|
||||||
|
Index Cond: (chat_id = (InitPlan 1).col1)
|
||||||
|
Filter: (ROW(created_at, id) > ROW('2026-01-01 00:30:00+00'::timestamp with time zone, '00000000-0000-0000-0000-000000000000'::uuid))
|
||||||
|
Rows Removed by Filter: 29
|
||||||
|
Index Searches: 1
|
||||||
|
Buffers: shared hit=10
|
||||||
|
Planning Time: 0.084 ms
|
||||||
|
Execution Time: 0.167 ms
|
||||||
|
(19 rows)
|
||||||
|
|
||||||
|
Time: 0.532 ms
|
||||||
|
research=# EXPLAIN (ANALYZE, BUFFERS) SELECT * FROM messages WHERE chat_id = (SELECT id FROM chats WHERE title = 'small-1') AND (created_at, id) > ('2026-01-01 00:30+00', '00000000-0000-0000-0000-000000000000') ORDER BY created_at, id LIMIT 50;
|
||||||
|
QUERY PLAN
|
||||||
|
-----------------------------------------------------------------------------------------------------------------------------------------------------
|
||||||
|
Limit (cost=819.50..819.63 rows=50 width=151) (actual time=0.126..0.131 rows=46.00 loops=1)
|
||||||
|
Buffers: shared hit=10
|
||||||
|
InitPlan 1
|
||||||
|
-> Seq Scan on chats (cost=0.00..4.58 rows=1 width=16) (actual time=0.032..0.042 rows=1.00 loops=1)
|
||||||
|
Filter: (title = 'small-1'::text)
|
||||||
|
Rows Removed by Filter: 205
|
||||||
|
Buffers: shared hit=2
|
||||||
|
-> Sort (cost=814.93..816.07 rows=456 width=151) (actual time=0.125..0.127 rows=46.00 loops=1)
|
||||||
|
Sort Key: messages.created_at, messages.id
|
||||||
|
Sort Method: quicksort Memory: 35kB
|
||||||
|
Buffers: shared hit=10
|
||||||
|
-> Index Scan using idx_messages_chat_id on messages (cost=0.42..799.78 rows=456 width=151) (actual time=0.075..0.086 rows=46.00 loops=1)
|
||||||
|
Index Cond: (chat_id = (InitPlan 1).col1)
|
||||||
|
Filter: (ROW(created_at, id) > ROW('2026-01-01 00:30:00+00'::timestamp with time zone, '00000000-0000-0000-0000-000000000000'::uuid))
|
||||||
|
Rows Removed by Filter: 29
|
||||||
|
Index Searches: 1
|
||||||
|
Buffers: shared hit=10
|
||||||
|
Planning Time: 0.250 ms
|
||||||
|
Execution Time: 0.166 ms
|
||||||
|
(19 rows)
|
||||||
|
|
||||||
|
Time: 1.156 ms
|
||||||
|
|
||||||
|
|
||||||
|
B. (chat_id, created_at, id)
|
||||||
|
research=# DROP INDEX IF EXISTS idx_messages_chat_id;
|
||||||
|
DROP INDEX
|
||||||
|
Time: 3.644 ms
|
||||||
|
research=# CREATE INDEX idx_messages_chat_history ON messages (chat_id, created_at, id);
|
||||||
|
CREATE INDEX
|
||||||
|
Time: 69.022 ms
|
||||||
|
research=# ANALYZE messages;
|
||||||
|
ANALYZE
|
||||||
|
Time: 103.435 ms
|
||||||
|
research=# EXPLAIN (ANALYZE, BUFFERS) SELECT * FROM messages WHERE chat_id = (SELECT id FROM chats WHERE title = 'big') AND (created_at, id) > ('2026-01-15 00:00+00', '00000000-0000-0000-0000-000000000000') ORDER BY created_at, id LIMIT 50;
|
||||||
|
QUERY PLAN
|
||||||
|
---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
|
||||||
|
Limit (cost=4.99..93.65 rows=50 width=151) (actual time=0.055..0.069 rows=50.00 loops=1)
|
||||||
|
Buffers: shared hit=4 read=4
|
||||||
|
InitPlan 1
|
||||||
|
-> Seq Scan on chats (cost=0.00..4.58 rows=1 width=16) (actual time=0.009..0.019 rows=1.00 loops=1)
|
||||||
|
Filter: (title = 'big'::text)
|
||||||
|
Rows Removed by Filter: 205
|
||||||
|
Buffers: shared hit=2
|
||||||
|
-> Index Scan using idx_messages_chat_history on messages (cost=0.42..340.85 rows=192 width=151) (actual time=0.054..0.065 rows=50.00 loops=1)
|
||||||
|
Index Cond: ((chat_id = (InitPlan 1).col1) AND (ROW(created_at, id) > ROW('2026-01-15 00:00:00+00'::timestamp with time zone, '00000000-0000-0000-0000-000000000000'::uuid)))
|
||||||
|
Index Searches: 1
|
||||||
|
Buffers: shared hit=4 read=4
|
||||||
|
Planning:
|
||||||
|
Buffers: shared hit=21 read=1
|
||||||
|
Planning Time: 0.333 ms
|
||||||
|
Execution Time: 0.092 ms
|
||||||
|
(15 rows)
|
||||||
|
|
||||||
|
Time: 1.018 ms
|
||||||
|
research=# EXPLAIN (ANALYZE, BUFFERS) SELECT * FROM messages WHERE chat_id = (SELECT id FROM chats WHERE title = 'big') AND (created_at, id) > ('2026-01-15 00:00+00', '00000000-0000-0000-0000-000000000000') ORDER BY created_at, id LIMIT 50;
|
||||||
|
QUERY PLAN
|
||||||
|
---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
|
||||||
|
Limit (cost=4.99..93.65 rows=50 width=151) (actual time=0.033..0.045 rows=50.00 loops=1)
|
||||||
|
Buffers: shared hit=8
|
||||||
|
InitPlan 1
|
||||||
|
-> Seq Scan on chats (cost=0.00..4.58 rows=1 width=16) (actual time=0.011..0.020 rows=1.00 loops=1)
|
||||||
|
Filter: (title = 'big'::text)
|
||||||
|
Rows Removed by Filter: 205
|
||||||
|
Buffers: shared hit=2
|
||||||
|
-> Index Scan using idx_messages_chat_history on messages (cost=0.42..340.85 rows=192 width=151) (actual time=0.032..0.041 rows=50.00 loops=1)
|
||||||
|
Index Cond: ((chat_id = (InitPlan 1).col1) AND (ROW(created_at, id) > ROW('2026-01-15 00:00:00+00'::timestamp with time zone, '00000000-0000-0000-0000-000000000000'::uuid)))
|
||||||
|
Index Searches: 1
|
||||||
|
Buffers: shared hit=8
|
||||||
|
Planning Time: 0.106 ms
|
||||||
|
Execution Time: 0.061 ms
|
||||||
|
(13 rows)
|
||||||
|
|
||||||
|
Time: 0.464 ms
|
||||||
|
research=# EXPLAIN (ANALYZE, BUFFERS) SELECT * FROM messages WHERE chat_id = (SELECT id FROM chats WHERE title = 'small-1') AND (created_at, id) > ('2026-01-01 00:30+00', '00000000-0000-0000-0000-000000000000') ORDER BY created_at, id LIMIT 50;
|
||||||
|
QUERY PLAN
|
||||||
|
---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
|
||||||
|
Limit (cost=4.99..88.31 rows=50 width=151) (actual time=0.139..0.152 rows=46.00 loops=1)
|
||||||
|
Buffers: shared hit=7 read=2
|
||||||
|
InitPlan 1
|
||||||
|
-> Seq Scan on chats (cost=0.00..4.58 rows=1 width=16) (actual time=0.015..0.026 rows=1.00 loops=1)
|
||||||
|
Filter: (title = 'small-1'::text)
|
||||||
|
Rows Removed by Filter: 205
|
||||||
|
Buffers: shared hit=2
|
||||||
|
-> Index Scan using idx_messages_chat_history on messages (cost=0.42..758.65 rows=455 width=151) (actual time=0.137..0.147 rows=46.00 loops=1)
|
||||||
|
Index Cond: ((chat_id = (InitPlan 1).col1) AND (ROW(created_at, id) > ROW('2026-01-01 00:30:00+00'::timestamp with time zone, '00000000-0000-0000-0000-000000000000'::uuid)))
|
||||||
|
Index Searches: 1
|
||||||
|
Buffers: shared hit=7 read=2
|
||||||
|
Planning Time: 0.130 ms
|
||||||
|
Execution Time: 0.174 ms
|
||||||
|
(13 rows)
|
||||||
|
|
||||||
|
Time: 0.581 ms
|
||||||
|
research=# EXPLAIN (ANALYZE, BUFFERS) SELECT * FROM messages WHERE chat_id = (SELECT id FROM chats WHERE title = 'small-1') AND (created_at, id) > ('2026-01-01 00:30+00', '00000000-0000-0000-0000-000000000000') ORDER BY created_at, id LIMIT 50;
|
||||||
|
QUERY PLAN
|
||||||
|
---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
|
||||||
|
Limit (cost=4.99..88.31 rows=50 width=151) (actual time=0.064..0.073 rows=46.00 loops=1)
|
||||||
|
Buffers: shared hit=9
|
||||||
|
InitPlan 1
|
||||||
|
-> Seq Scan on chats (cost=0.00..4.58 rows=1 width=16) (actual time=0.030..0.039 rows=1.00 loops=1)
|
||||||
|
Filter: (title = 'small-1'::text)
|
||||||
|
Rows Removed by Filter: 205
|
||||||
|
Buffers: shared hit=2
|
||||||
|
-> Index Scan using idx_messages_chat_history on messages (cost=0.42..758.65 rows=455 width=151) (actual time=0.063..0.069 rows=46.00 loops=1)
|
||||||
|
Index Cond: ((chat_id = (InitPlan 1).col1) AND (ROW(created_at, id) > ROW('2026-01-01 00:30:00+00'::timestamp with time zone, '00000000-0000-0000-0000-000000000000'::uuid)))
|
||||||
|
Index Searches: 1
|
||||||
|
Buffers: shared hit=9
|
||||||
|
Planning Time: 0.208 ms
|
||||||
|
Execution Time: 0.100 ms
|
||||||
|
(13 rows)
|
||||||
|
|
||||||
|
Time: 0.808 ms
|
||||||
|
|
||||||
|
A. Only PK
|
||||||
|
research=# DROP INDEX IF EXISTS idx_messages_chat_history;
|
||||||
|
DROP INDEX
|
||||||
|
Time: 5.715 ms
|
||||||
|
research=# DROP INDEX IF EXISTS idx_messages_chat_id;
|
||||||
|
NOTICE: index "idx_messages_chat_id" does not exist, skipping
|
||||||
|
DROP INDEX
|
||||||
|
Time: 0.228 ms
|
||||||
|
research=# ANALYZE messages;
|
||||||
|
ANALYZE
|
||||||
|
Time: 102.311 ms
|
||||||
|
research=# EXPLAIN (ANALYZE, BUFFERS) SELECT * FROM messages WHERE chat_id = (SELECT id FROM chats WHERE title = 'big') AND (created_at, id) > ('2026-01-15 00:00+00', '00000000-0000-0000-0000-000000000000') ORDER BY created_at, id LIMIT 50;
|
||||||
|
QUERY PLAN
|
||||||
|
-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
|
||||||
|
Limit (cost=4022.99..4023.11 rows=50 width=150) (actual time=10.619..10.625 rows=50.00 loops=1)
|
||||||
|
Buffers: shared hit=2264
|
||||||
|
InitPlan 1
|
||||||
|
-> Seq Scan on chats (cost=0.00..4.58 rows=1 width=16) (actual time=0.007..0.019 rows=1.00 loops=1)
|
||||||
|
Filter: (title = 'big'::text)
|
||||||
|
Rows Removed by Filter: 205
|
||||||
|
Buffers: shared hit=2
|
||||||
|
-> Sort (cost=4018.41..4018.89 rows=193 width=150) (actual time=10.616..10.619 rows=50.00 loops=1)
|
||||||
|
Sort Key: messages.created_at, messages.id
|
||||||
|
Sort Method: top-N heapsort Memory: 36kB
|
||||||
|
Buffers: shared hit=2264
|
||||||
|
-> Seq Scan on messages (cost=0.00..4012.00 rows=193 width=150) (actual time=1.644..8.293 rows=39841.00 loops=1)
|
||||||
|
Filter: ((chat_id = (InitPlan 1).col1) AND (ROW(created_at, id) > ROW('2026-01-15 00:00:00+00'::timestamp with time zone, '00000000-0000-0000-0000-000000000000'::uuid)))
|
||||||
|
Rows Removed by Filter: 60159
|
||||||
|
Buffers: shared hit=2264
|
||||||
|
Planning:
|
||||||
|
Buffers: shared hit=20
|
||||||
|
Planning Time: 0.264 ms
|
||||||
|
Execution Time: 10.659 ms
|
||||||
|
(19 rows)
|
||||||
|
|
||||||
|
Time: 11.410 ms
|
||||||
|
research=# EXPLAIN (ANALYZE, BUFFERS) SELECT * FROM messages WHERE chat_id = (SELECT id FROM chats WHERE title = 'big') AND (created_at, id) > ('2026-01-15 00:00+00', '00000000-0000-0000-0000-000000000000') ORDER BY created_at, id LIMIT 50;
|
||||||
|
QUERY PLAN
|
||||||
|
-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
|
||||||
|
Limit (cost=4022.99..4023.11 rows=50 width=150) (actual time=10.266..10.274 rows=50.00 loops=1)
|
||||||
|
Buffers: shared hit=2264
|
||||||
|
InitPlan 1
|
||||||
|
-> Seq Scan on chats (cost=0.00..4.58 rows=1 width=16) (actual time=0.006..0.016 rows=1.00 loops=1)
|
||||||
|
Filter: (title = 'big'::text)
|
||||||
|
Rows Removed by Filter: 205
|
||||||
|
Buffers: shared hit=2
|
||||||
|
-> Sort (cost=4018.41..4018.89 rows=193 width=150) (actual time=10.265..10.269 rows=50.00 loops=1)
|
||||||
|
Sort Key: messages.created_at, messages.id
|
||||||
|
Sort Method: top-N heapsort Memory: 36kB
|
||||||
|
Buffers: shared hit=2264
|
||||||
|
-> Seq Scan on messages (cost=0.00..4012.00 rows=193 width=150) (actual time=1.597..8.150 rows=39841.00 loops=1)
|
||||||
|
Filter: ((chat_id = (InitPlan 1).col1) AND (ROW(created_at, id) > ROW('2026-01-15 00:00:00+00'::timestamp with time zone, '00000000-0000-0000-0000-000000000000'::uuid)))
|
||||||
|
Rows Removed by Filter: 60159
|
||||||
|
Buffers: shared hit=2264
|
||||||
|
Planning Time: 0.082 ms
|
||||||
|
Execution Time: 10.300 ms
|
||||||
|
(17 rows)
|
||||||
|
|
||||||
|
Time: 11.458 ms
|
||||||
|
research=# EXPLAIN (ANALYZE, BUFFERS) SELECT * FROM messages WHERE chat_id = (SELECT id FROM chats WHERE title = 'small-1') AND (created_at, id) > ('2026-01-01 00:30+00', '00000000-0000-0000-0000-000000000000') ORDER BY created_at, id LIMIT 50;
|
||||||
|
QUERY PLAN
|
||||||
|
-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
|
||||||
|
Limit (cost=4031.69..4031.81 rows=50 width=150) (actual time=6.337..6.344 rows=46.00 loops=1)
|
||||||
|
Buffers: shared hit=2264
|
||||||
|
InitPlan 1
|
||||||
|
-> Seq Scan on chats (cost=0.00..4.58 rows=1 width=16) (actual time=0.007..0.019 rows=1.00 loops=1)
|
||||||
|
Filter: (title = 'small-1'::text)
|
||||||
|
Rows Removed by Filter: 205
|
||||||
|
Buffers: shared hit=2
|
||||||
|
-> Sort (cost=4027.11..4028.25 rows=455 width=150) (actual time=6.335..6.339 rows=46.00 loops=1)
|
||||||
|
Sort Key: messages.created_at, messages.id
|
||||||
|
Sort Method: quicksort Memory: 35kB
|
||||||
|
Buffers: shared hit=2264
|
||||||
|
-> Seq Scan on messages (cost=0.00..4012.00 rows=455 width=150) (actual time=4.345..6.255 rows=46.00 loops=1)
|
||||||
|
Filter: ((chat_id = (InitPlan 1).col1) AND (ROW(created_at, id) > ROW('2026-01-01 00:30:00+00'::timestamp with time zone, '00000000-0000-0000-0000-000000000000'::uuid)))
|
||||||
|
Rows Removed by Filter: 99954
|
||||||
|
Buffers: shared hit=2264
|
||||||
|
Planning Time: 0.105 ms
|
||||||
|
Execution Time: 6.366 ms
|
||||||
|
(17 rows)
|
||||||
|
|
||||||
|
Time: 6.763 ms
|
||||||
|
research=# EXPLAIN (ANALYZE, BUFFERS) SELECT * FROM messages WHERE chat_id = (SELECT id FROM chats WHERE title = 'small-1') AND (created_at, id) > ('2026-01-01 00:30+00', '00000000-0000-0000-0000-000000000000') ORDER BY created_at, id LIMIT 50;
|
||||||
|
QUERY PLAN
|
||||||
|
-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
|
||||||
|
Limit (cost=4031.69..4031.81 rows=50 width=150) (actual time=6.219..6.227 rows=46.00 loops=1)
|
||||||
|
Buffers: shared hit=2264
|
||||||
|
InitPlan 1
|
||||||
|
-> Seq Scan on chats (cost=0.00..4.58 rows=1 width=16) (actual time=0.009..0.021 rows=1.00 loops=1)
|
||||||
|
Filter: (title = 'small-1'::text)
|
||||||
|
Rows Removed by Filter: 205
|
||||||
|
Buffers: shared hit=2
|
||||||
|
-> Sort (cost=4027.11..4028.25 rows=455 width=150) (actual time=6.217..6.221 rows=46.00 loops=1)
|
||||||
|
Sort Key: messages.created_at, messages.id
|
||||||
|
Sort Method: quicksort Memory: 35kB
|
||||||
|
Buffers: shared hit=2264
|
||||||
|
-> Seq Scan on messages (cost=0.00..4012.00 rows=455 width=150) (actual time=4.517..6.205 rows=46.00 loops=1)
|
||||||
|
Filter: ((chat_id = (InitPlan 1).col1) AND (ROW(created_at, id) > ROW('2026-01-01 00:30:00+00'::timestamp with time zone, '00000000-0000-0000-0000-000000000000'::uuid)))
|
||||||
|
Rows Removed by Filter: 99954
|
||||||
|
Buffers: shared hit=2264
|
||||||
|
Planning Time: 0.110 ms
|
||||||
|
Execution Time: 6.248 ms
|
||||||
|
(17 rows)
|
||||||
|
|
||||||
|
Time: 6.727 ms
|
||||||
@@ -0,0 +1,168 @@
|
|||||||
|
> docker compose exec postgres psql -U messenger -d postgres -c "CREATE DATABASE research;"
|
||||||
|
CREATE DATABASE
|
||||||
|
> docker compose run --rm --no-deps --entrypoint sh migrate -c 'URL=$(sed s,/messenger?,/research?, /run/secrets/database_url); goose -dir /migrations postgres $URL up'
|
||||||
|
Container mtusi2026lab2-migrate-run-37c6222942bf Creating
|
||||||
|
Container mtusi2026lab2-migrate-run-37c6222942bf Created
|
||||||
|
2026/10/07 19:30:06 OK 00001_init.sql (10.96ms)
|
||||||
|
2026/10/07 19:30:06 goose: successfully migrated database to version: 1
|
||||||
|
> docker compose exec postgres psql -U messenger -d research
|
||||||
|
psql (18.6 (Debian 18.6-1.pgdg13+2))
|
||||||
|
Type "help" for help.
|
||||||
|
|
||||||
|
research=# INSERT INTO users (id, username, display_name, password_hash) VALUES (uuidv7(), 'research_user', 'Research User', 'x');
|
||||||
|
INSERT 0 1
|
||||||
|
research=# INSERT INTO chats (id, title) SELECT uuidv7(), 'big';
|
||||||
|
INSERT 0 1
|
||||||
|
research=# INSERT INTO chats (id, title) SELECT uuidv7(), 'mid-' || g FROM generate_series(1, 5) g;
|
||||||
|
INSERT 0 5
|
||||||
|
research=# INSERT INTO chats (id, title) SELECT uuidv7(), 'small-' || g FROM generate_series(1, 200) g;
|
||||||
|
INSERT 0 200
|
||||||
|
research=# CREATE TABLE messages_seed AS
|
||||||
|
SELECT uuidv7() AS id,
|
||||||
|
c.id AS chat_id,
|
||||||
|
(SELECT id FROM users WHERE username = 'research_user') AS sender_id,
|
||||||
|
'message ' || n || ' ' || repeat(md5(random()::text), 1 + (n % 4)) AS text,
|
||||||
|
timestamptz '2026-01-01 00:00:00+00' + n * interval '1 minute' AS created_at
|
||||||
|
FROM chats c
|
||||||
|
CROSS JOIN LATERAL generate_series(1, CASE split_part(c.title, '-', 1)
|
||||||
|
WHEN 'big' THEN 60000 WHEN 'mid' THEN 5000 ELSE 75 END) AS n;
|
||||||
|
SELECT 100000
|
||||||
|
|
||||||
|
A. Only PK
|
||||||
|
research=# SELECT 'VARIANT A' AS variant;
|
||||||
|
DROP INDEX IF EXISTS idx_messages_chat_history;
|
||||||
|
DROP INDEX IF EXISTS idx_messages_chat_id;
|
||||||
|
|
||||||
|
TRUNCATE messages;
|
||||||
|
INSERT INTO messages SELECT id, chat_id, sender_id, text, created_at FROM messages_seed;
|
||||||
|
TRUNCATE messages;
|
||||||
|
INSERT INTO messages SELECT id, chat_id, sender_id, text, created_at FROM messages_seed;
|
||||||
|
TRUNCATE messages;
|
||||||
|
INSERT INTO messages SELECT id, chat_id, sender_id, text, created_at FROM messages_seed;
|
||||||
|
|
||||||
|
ANALYZE messages;
|
||||||
|
SELECT pg_size_pretty(pg_relation_size('messages')) AS table, indexrelid::regclass AS idx, pg_size_pretty(pg_relation_size(indexrelid)) AS size FROM pg_index WHERE indrelid = 'messages'::regclass;
|
||||||
|
variant
|
||||||
|
-----------
|
||||||
|
VARIANT A
|
||||||
|
(1 row)
|
||||||
|
|
||||||
|
Time: 0.345 ms
|
||||||
|
DROP INDEX
|
||||||
|
Time: 5.736 ms
|
||||||
|
NOTICE: index "idx_messages_chat_id" does not exist, skipping
|
||||||
|
DROP INDEX
|
||||||
|
Time: 0.153 ms
|
||||||
|
TRUNCATE TABLE
|
||||||
|
Time: 3.614 ms
|
||||||
|
INSERT 0 100000
|
||||||
|
Time: 989.859 ms
|
||||||
|
TRUNCATE TABLE
|
||||||
|
Time: 6.348 ms
|
||||||
|
INSERT 0 100000
|
||||||
|
Time: 976.844 ms
|
||||||
|
TRUNCATE TABLE
|
||||||
|
Time: 6.268 ms
|
||||||
|
INSERT 0 100000
|
||||||
|
Time: 977.896 ms
|
||||||
|
ANALYZE
|
||||||
|
Time: 103.989 ms
|
||||||
|
table | idx | size
|
||||||
|
-------+---------------+---------
|
||||||
|
18 MB | messages_pkey | 3104 kB
|
||||||
|
(1 row)
|
||||||
|
|
||||||
|
Time: 0.765 ms
|
||||||
|
|
||||||
|
B. (chat_id, created_at, id)
|
||||||
|
research=# SELECT 'VARIANT B' AS variant;
|
||||||
|
DROP INDEX IF EXISTS idx_messages_chat_id;
|
||||||
|
CREATE INDEX idx_messages_chat_history ON messages (chat_id, created_at, id);
|
||||||
|
|
||||||
|
TRUNCATE messages;
|
||||||
|
INSERT INTO messages SELECT id, chat_id, sender_id, text, created_at FROM messages_seed;
|
||||||
|
TRUNCATE messages;
|
||||||
|
INSERT INTO messages SELECT id, chat_id, sender_id, text, created_at FROM messages_seed;
|
||||||
|
TRUNCATE messages;
|
||||||
|
INSERT INTO messages SELECT id, chat_id, sender_id, text, created_at FROM messages_seed;
|
||||||
|
|
||||||
|
ANALYZE messages;
|
||||||
|
SELECT pg_size_pretty(pg_relation_size('messages')) AS table, indexrelid::regclass AS idx, pg_size_pretty(pg_relation_size(indexrelid)) AS size FROM pg_index WHERE indrelid = 'messages'::regclass;
|
||||||
|
variant
|
||||||
|
-----------
|
||||||
|
VARIANT B
|
||||||
|
(1 row)
|
||||||
|
|
||||||
|
Time: 0.411 ms
|
||||||
|
NOTICE: index "idx_messages_chat_id" does not exist, skipping
|
||||||
|
DROP INDEX
|
||||||
|
Time: 0.144 ms
|
||||||
|
CREATE INDEX
|
||||||
|
Time: 165.646 ms
|
||||||
|
TRUNCATE TABLE
|
||||||
|
Time: 9.681 ms
|
||||||
|
INSERT 0 100000
|
||||||
|
Time: 1655.348 ms (00:01.655)
|
||||||
|
TRUNCATE TABLE
|
||||||
|
Time: 6.620 ms
|
||||||
|
INSERT 0 100000
|
||||||
|
Time: 1640.366 ms (00:01.640)
|
||||||
|
TRUNCATE TABLE
|
||||||
|
Time: 7.094 ms
|
||||||
|
INSERT 0 100000
|
||||||
|
Time: 1156.808 ms (00:01.157)
|
||||||
|
ANALYZE
|
||||||
|
Time: 92.376 ms
|
||||||
|
table | idx | size
|
||||||
|
-------+---------------------------+---------
|
||||||
|
18 MB | messages_pkey | 3104 kB
|
||||||
|
18 MB | idx_messages_chat_history | 5776 kB
|
||||||
|
(2 rows)
|
||||||
|
|
||||||
|
Time: 0.560 ms
|
||||||
|
|
||||||
|
C. (chat_id, id)
|
||||||
|
research=# SELECT 'VARIANT C' AS variant;
|
||||||
|
DROP INDEX IF EXISTS idx_messages_chat_history;
|
||||||
|
CREATE INDEX idx_messages_chat_id ON messages (chat_id, id);
|
||||||
|
|
||||||
|
TRUNCATE messages;
|
||||||
|
INSERT INTO messages SELECT id, chat_id, sender_id, text, created_at FROM messages_seed;
|
||||||
|
TRUNCATE messages;
|
||||||
|
INSERT INTO messages SELECT id, chat_id, sender_id, text, created_at FROM messages_seed;
|
||||||
|
TRUNCATE messages;
|
||||||
|
INSERT INTO messages SELECT id, chat_id, sender_id, text, created_at FROM messages_seed;
|
||||||
|
|
||||||
|
ANALYZE messages;
|
||||||
|
SELECT pg_size_pretty(pg_relation_size('messages')) AS table, indexrelid::regclass AS idx, pg_size_pretty(pg_relation_size(indexrelid)) AS size FROM pg_index WHERE indrelid = 'messages'::regclass;
|
||||||
|
variant
|
||||||
|
-----------
|
||||||
|
VARIANT C
|
||||||
|
(1 row)
|
||||||
|
|
||||||
|
Time: 0.362 ms
|
||||||
|
DROP INDEX
|
||||||
|
Time: 4.459 ms
|
||||||
|
CREATE INDEX
|
||||||
|
Time: 61.503 ms
|
||||||
|
TRUNCATE TABLE
|
||||||
|
Time: 6.046 ms
|
||||||
|
INSERT 0 100000
|
||||||
|
Time: 1222.658 ms (00:01.223)
|
||||||
|
TRUNCATE TABLE
|
||||||
|
Time: 6.482 ms
|
||||||
|
INSERT 0 100000
|
||||||
|
Time: 1181.280 ms (00:01.181)
|
||||||
|
TRUNCATE TABLE
|
||||||
|
Time: 6.286 ms
|
||||||
|
INSERT 0 100000
|
||||||
|
Time: 1185.066 ms (00:01.185)
|
||||||
|
ANALYZE
|
||||||
|
Time: 98.084 ms
|
||||||
|
table | idx | size
|
||||||
|
-------+----------------------+---------
|
||||||
|
18 MB | messages_pkey | 3104 kB
|
||||||
|
18 MB | idx_messages_chat_id | 4880 kB
|
||||||
|
(2 rows)
|
||||||
|
|
||||||
|
Time: 0.490 ms
|
||||||
+64
-15
@@ -116,7 +116,7 @@ func (q *Queries) IsChatMember(ctx context.Context, arg IsChatMemberParams) (boo
|
|||||||
return exists, err
|
return exists, err
|
||||||
}
|
}
|
||||||
|
|
||||||
const listChats = `-- name: ListChats :many
|
const listChatsAfter = `-- name: ListChatsAfter :many
|
||||||
SELECT
|
SELECT
|
||||||
c.id, c.title, c.created_at,
|
c.id, c.title, c.created_at,
|
||||||
ARRAY(
|
ARRAY(
|
||||||
@@ -127,33 +127,30 @@ SELECT
|
|||||||
FROM chats c
|
FROM chats c
|
||||||
JOIN chat_members m ON m.chat_id = c.id
|
JOIN chat_members m ON m.chat_id = c.id
|
||||||
WHERE m.user_id = $1
|
WHERE m.user_id = $1
|
||||||
AND (
|
AND (c.created_at, c.id) > (
|
||||||
$2::timestamptz IS NULL
|
$2::timestamptz,
|
||||||
OR (c.created_at, c.id) > (
|
$3::uuid
|
||||||
$2::timestamptz,
|
|
||||||
$3::uuid
|
|
||||||
)
|
|
||||||
)
|
)
|
||||||
ORDER BY c.created_at, c.id
|
ORDER BY c.created_at, c.id
|
||||||
LIMIT $4
|
LIMIT $4
|
||||||
`
|
`
|
||||||
|
|
||||||
type ListChatsParams struct {
|
type ListChatsAfterParams struct {
|
||||||
UserID uuid.UUID
|
UserID uuid.UUID
|
||||||
AfterCreatedAt *time.Time
|
AfterCreatedAt time.Time
|
||||||
AfterID *uuid.UUID
|
AfterID uuid.UUID
|
||||||
Lim int32
|
Lim int32
|
||||||
}
|
}
|
||||||
|
|
||||||
type ListChatsRow struct {
|
type ListChatsAfterRow struct {
|
||||||
ID uuid.UUID
|
ID uuid.UUID
|
||||||
Title string
|
Title string
|
||||||
CreatedAt time.Time
|
CreatedAt time.Time
|
||||||
MemberIds []uuid.UUID
|
MemberIds []uuid.UUID
|
||||||
}
|
}
|
||||||
|
|
||||||
func (q *Queries) ListChats(ctx context.Context, arg ListChatsParams) ([]ListChatsRow, error) {
|
func (q *Queries) ListChatsAfter(ctx context.Context, arg ListChatsAfterParams) ([]ListChatsAfterRow, error) {
|
||||||
rows, err := q.db.Query(ctx, listChats,
|
rows, err := q.db.Query(ctx, listChatsAfter,
|
||||||
arg.UserID,
|
arg.UserID,
|
||||||
arg.AfterCreatedAt,
|
arg.AfterCreatedAt,
|
||||||
arg.AfterID,
|
arg.AfterID,
|
||||||
@@ -163,9 +160,61 @@ func (q *Queries) ListChats(ctx context.Context, arg ListChatsParams) ([]ListCha
|
|||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
defer rows.Close()
|
defer rows.Close()
|
||||||
items := []ListChatsRow{}
|
items := []ListChatsAfterRow{}
|
||||||
for rows.Next() {
|
for rows.Next() {
|
||||||
var i ListChatsRow
|
var i ListChatsAfterRow
|
||||||
|
if err := rows.Scan(
|
||||||
|
&i.ID,
|
||||||
|
&i.Title,
|
||||||
|
&i.CreatedAt,
|
||||||
|
&i.MemberIds,
|
||||||
|
); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
items = append(items, i)
|
||||||
|
}
|
||||||
|
if err := rows.Err(); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
return items, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
const listChatsFirstPage = `-- name: ListChatsFirstPage :many
|
||||||
|
SELECT
|
||||||
|
c.id, c.title, c.created_at,
|
||||||
|
ARRAY(
|
||||||
|
SELECT cm.user_id FROM chat_members cm
|
||||||
|
WHERE cm.chat_id = c.id
|
||||||
|
ORDER BY cm.user_id
|
||||||
|
)::uuid[] AS member_ids
|
||||||
|
FROM chats c
|
||||||
|
JOIN chat_members m ON m.chat_id = c.id
|
||||||
|
WHERE m.user_id = $1
|
||||||
|
ORDER BY c.created_at, c.id
|
||||||
|
LIMIT $2
|
||||||
|
`
|
||||||
|
|
||||||
|
type ListChatsFirstPageParams struct {
|
||||||
|
UserID uuid.UUID
|
||||||
|
Lim int32
|
||||||
|
}
|
||||||
|
|
||||||
|
type ListChatsFirstPageRow struct {
|
||||||
|
ID uuid.UUID
|
||||||
|
Title string
|
||||||
|
CreatedAt time.Time
|
||||||
|
MemberIds []uuid.UUID
|
||||||
|
}
|
||||||
|
|
||||||
|
func (q *Queries) ListChatsFirstPage(ctx context.Context, arg ListChatsFirstPageParams) ([]ListChatsFirstPageRow, error) {
|
||||||
|
rows, err := q.db.Query(ctx, listChatsFirstPage, arg.UserID, arg.Lim)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
defer rows.Close()
|
||||||
|
items := []ListChatsFirstPageRow{}
|
||||||
|
for rows.Next() {
|
||||||
|
var i ListChatsFirstPageRow
|
||||||
if err := rows.Scan(
|
if err := rows.Scan(
|
||||||
&i.ID,
|
&i.ID,
|
||||||
&i.Title,
|
&i.Title,
|
||||||
|
|||||||
+47
-12
@@ -57,29 +57,26 @@ func (q *Queries) CreateMessage(ctx context.Context, arg CreateMessageParams) (M
|
|||||||
return i, err
|
return i, err
|
||||||
}
|
}
|
||||||
|
|
||||||
const listMessages = `-- name: ListMessages :many
|
const listMessagesAfter = `-- name: ListMessagesAfter :many
|
||||||
SELECT id, chat_id, sender_id, text, created_at FROM messages
|
SELECT id, chat_id, sender_id, text, created_at FROM messages
|
||||||
WHERE chat_id = $1
|
WHERE chat_id = $1
|
||||||
AND (
|
AND (created_at, id) > (
|
||||||
$2::timestamptz IS NULL
|
$2::timestamptz,
|
||||||
OR (created_at, id) > (
|
$3::uuid
|
||||||
$2::timestamptz,
|
|
||||||
$3::uuid
|
|
||||||
)
|
|
||||||
)
|
)
|
||||||
ORDER BY created_at, id
|
ORDER BY created_at, id
|
||||||
LIMIT $4
|
LIMIT $4
|
||||||
`
|
`
|
||||||
|
|
||||||
type ListMessagesParams struct {
|
type ListMessagesAfterParams struct {
|
||||||
ChatID uuid.UUID
|
ChatID uuid.UUID
|
||||||
AfterCreatedAt *time.Time
|
AfterCreatedAt time.Time
|
||||||
AfterID *uuid.UUID
|
AfterID uuid.UUID
|
||||||
Lim int32
|
Lim int32
|
||||||
}
|
}
|
||||||
|
|
||||||
func (q *Queries) ListMessages(ctx context.Context, arg ListMessagesParams) ([]Message, error) {
|
func (q *Queries) ListMessagesAfter(ctx context.Context, arg ListMessagesAfterParams) ([]Message, error) {
|
||||||
rows, err := q.db.Query(ctx, listMessages,
|
rows, err := q.db.Query(ctx, listMessagesAfter,
|
||||||
arg.ChatID,
|
arg.ChatID,
|
||||||
arg.AfterCreatedAt,
|
arg.AfterCreatedAt,
|
||||||
arg.AfterID,
|
arg.AfterID,
|
||||||
@@ -108,3 +105,41 @@ func (q *Queries) ListMessages(ctx context.Context, arg ListMessagesParams) ([]M
|
|||||||
}
|
}
|
||||||
return items, nil
|
return items, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const listMessagesFirstPage = `-- name: ListMessagesFirstPage :many
|
||||||
|
SELECT id, chat_id, sender_id, text, created_at FROM messages
|
||||||
|
WHERE chat_id = $1
|
||||||
|
ORDER BY created_at, id
|
||||||
|
LIMIT $2
|
||||||
|
`
|
||||||
|
|
||||||
|
type ListMessagesFirstPageParams struct {
|
||||||
|
ChatID uuid.UUID
|
||||||
|
Lim int32
|
||||||
|
}
|
||||||
|
|
||||||
|
func (q *Queries) ListMessagesFirstPage(ctx context.Context, arg ListMessagesFirstPageParams) ([]Message, error) {
|
||||||
|
rows, err := q.db.Query(ctx, listMessagesFirstPage, arg.ChatID, arg.Lim)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
defer rows.Close()
|
||||||
|
items := []Message{}
|
||||||
|
for rows.Next() {
|
||||||
|
var i Message
|
||||||
|
if err := rows.Scan(
|
||||||
|
&i.ID,
|
||||||
|
&i.ChatID,
|
||||||
|
&i.SenderID,
|
||||||
|
&i.Text,
|
||||||
|
&i.CreatedAt,
|
||||||
|
); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
items = append(items, i)
|
||||||
|
}
|
||||||
|
if err := rows.Err(); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
return items, nil
|
||||||
|
}
|
||||||
|
|||||||
@@ -62,15 +62,20 @@ func (q *Queries) DeleteSession(ctx context.Context, tokenHash string) (int64, e
|
|||||||
return result.RowsAffected(), nil
|
return result.RowsAffected(), nil
|
||||||
}
|
}
|
||||||
|
|
||||||
const getSessionUserID = `-- name: GetSessionUserID :one
|
const getActiveSession = `-- name: GetActiveSession :one
|
||||||
SELECT user_id FROM sessions
|
SELECT user_id, expires_at FROM sessions
|
||||||
WHERE token_hash = $1
|
WHERE token_hash = $1
|
||||||
AND expires_at > now()
|
AND expires_at > now()
|
||||||
`
|
`
|
||||||
|
|
||||||
func (q *Queries) GetSessionUserID(ctx context.Context, tokenHash string) (uuid.UUID, error) {
|
type GetActiveSessionRow struct {
|
||||||
row := q.db.QueryRow(ctx, getSessionUserID, tokenHash)
|
UserID uuid.UUID
|
||||||
var user_id uuid.UUID
|
ExpiresAt time.Time
|
||||||
err := row.Scan(&user_id)
|
}
|
||||||
return user_id, err
|
|
||||||
|
func (q *Queries) GetActiveSession(ctx context.Context, tokenHash string) (GetActiveSessionRow, error) {
|
||||||
|
row := q.db.QueryRow(ctx, getActiveSession, tokenHash)
|
||||||
|
var i GetActiveSessionRow
|
||||||
|
err := row.Scan(&i.UserID, &i.ExpiresAt)
|
||||||
|
return i, err
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -2,6 +2,8 @@ package httpx
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"encoding/json"
|
"encoding/json"
|
||||||
|
"errors"
|
||||||
|
"io"
|
||||||
"mime"
|
"mime"
|
||||||
"net/http"
|
"net/http"
|
||||||
|
|
||||||
@@ -25,5 +27,10 @@ func DecodeJSONBody(w http.ResponseWriter, r *http.Request, requestID string, ds
|
|||||||
return false
|
return false
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if err := decoder.Decode(&struct{}{}); !errors.Is(err, io.EOF) {
|
||||||
|
WriteError(w, http.StatusBadRequest, dto.ErrorCodeInvalidRequest, "invalid request body", requestID)
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
|
||||||
return true
|
return true
|
||||||
}
|
}
|
||||||
|
|||||||
+10
-14
@@ -26,7 +26,7 @@ var (
|
|||||||
type authQueries interface {
|
type authQueries interface {
|
||||||
CreateSession(ctx context.Context, arg db.CreateSessionParams) error
|
CreateSession(ctx context.Context, arg db.CreateSessionParams) error
|
||||||
DeleteSession(ctx context.Context, tokenHash string) (int64, error)
|
DeleteSession(ctx context.Context, tokenHash string) (int64, error)
|
||||||
GetSessionUserID(ctx context.Context, tokenHash string) (uuid.UUID, error)
|
GetActiveSession(ctx context.Context, tokenHash string) (db.GetActiveSessionRow, error)
|
||||||
GetUserByUsername(ctx context.Context, username string) (db.User, error)
|
GetUserByUsername(ctx context.Context, username string) (db.User, error)
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -107,7 +107,7 @@ func (s *AuthService) Authenticate(ctx context.Context, token string) (uuid.UUID
|
|||||||
s.log.Warn("session cache get failed, falling back to database", "error", err)
|
s.log.Warn("session cache get failed, falling back to database", "error", err)
|
||||||
}
|
}
|
||||||
|
|
||||||
userID, err := s.q.GetSessionUserID(ctx, tokenHash)
|
row, err := s.q.GetActiveSession(ctx, tokenHash)
|
||||||
if postgres.IsNotFound(err) {
|
if postgres.IsNotFound(err) {
|
||||||
return uuid.Nil, ErrUnauthorized
|
return uuid.Nil, ErrUnauthorized
|
||||||
}
|
}
|
||||||
@@ -115,13 +115,16 @@ func (s *AuthService) Authenticate(ctx context.Context, token string) (uuid.UUID
|
|||||||
return uuid.Nil, err
|
return uuid.Nil, err
|
||||||
}
|
}
|
||||||
|
|
||||||
cctx, cancel = context.WithTimeout(ctx, cacheOpTimeout)
|
ttl := min(time.Until(row.ExpiresAt), sessionCacheTTL)
|
||||||
if err := s.cache.Set(cctx, key, userID.String(), s.cacheTTL()).Err(); err != nil {
|
if ttl > 0 {
|
||||||
s.log.Warn("session cache set failed", "error", err)
|
cctx, cancel = context.WithTimeout(ctx, cacheOpTimeout)
|
||||||
|
if err := s.cache.Set(cctx, key, row.UserID.String(), ttl).Err(); err != nil {
|
||||||
|
s.log.Warn("session cache set failed", "error", err)
|
||||||
|
}
|
||||||
|
cancel()
|
||||||
}
|
}
|
||||||
cancel()
|
|
||||||
|
|
||||||
return userID, nil
|
return row.UserID, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func (s *AuthService) Logout(ctx context.Context, token string) error {
|
func (s *AuthService) Logout(ctx context.Context, token string) error {
|
||||||
@@ -147,10 +150,3 @@ func (s *AuthService) Logout(ctx context.Context, token string) error {
|
|||||||
func cacheKey(tokenHash string) string {
|
func cacheKey(tokenHash string) string {
|
||||||
return "session:" + tokenHash
|
return "session:" + tokenHash
|
||||||
}
|
}
|
||||||
|
|
||||||
func (s *AuthService) cacheTTL() time.Duration {
|
|
||||||
if s.sessionTTL < sessionCacheTTL {
|
|
||||||
return s.sessionTTL
|
|
||||||
}
|
|
||||||
return sessionCacheTTL
|
|
||||||
}
|
|
||||||
|
|||||||
+46
-33
@@ -5,7 +5,6 @@ import (
|
|||||||
"context"
|
"context"
|
||||||
"errors"
|
"errors"
|
||||||
"slices"
|
"slices"
|
||||||
"time"
|
|
||||||
|
|
||||||
"github.com/google/uuid"
|
"github.com/google/uuid"
|
||||||
"github.com/jackc/pgx/v5"
|
"github.com/jackc/pgx/v5"
|
||||||
@@ -27,7 +26,8 @@ type chatQueries interface {
|
|||||||
AddChatMembers(ctx context.Context, arg db.AddChatMembersParams) error
|
AddChatMembers(ctx context.Context, arg db.AddChatMembersParams) error
|
||||||
CreateChat(ctx context.Context, arg db.CreateChatParams) (db.Chat, error)
|
CreateChat(ctx context.Context, arg db.CreateChatParams) (db.Chat, error)
|
||||||
GetChat(ctx context.Context, arg db.GetChatParams) (db.GetChatRow, error)
|
GetChat(ctx context.Context, arg db.GetChatParams) (db.GetChatRow, error)
|
||||||
ListChats(ctx context.Context, arg db.ListChatsParams) ([]db.ListChatsRow, error)
|
ListChatsAfter(ctx context.Context, arg db.ListChatsAfterParams) ([]db.ListChatsAfterRow, error)
|
||||||
|
ListChatsFirstPage(ctx context.Context, arg db.ListChatsFirstPageParams) ([]db.ListChatsFirstPageRow, error)
|
||||||
}
|
}
|
||||||
|
|
||||||
type txBeginner interface {
|
type txBeginner interface {
|
||||||
@@ -142,48 +142,61 @@ func (s *ChatService) List(
|
|||||||
limit int,
|
limit int,
|
||||||
cursor *string,
|
cursor *string,
|
||||||
) ([]model.Chat, *string, error) {
|
) ([]model.Chat, *string, error) {
|
||||||
var afterCreatedAt *time.Time
|
var chats []model.Chat
|
||||||
var afterID *uuid.UUID
|
|
||||||
|
|
||||||
if cursor != nil {
|
if cursor == nil {
|
||||||
decoded, err := decodeCursor(*cursor, uuid.Nil)
|
rows, err := s.q.ListChatsFirstPage(ctx, db.ListChatsFirstPageParams{
|
||||||
|
UserID: userID,
|
||||||
|
Lim: int32(limit + 1),
|
||||||
|
})
|
||||||
if err != nil {
|
if err != nil {
|
||||||
|
return nil, nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
chats = make([]model.Chat, 0, len(rows))
|
||||||
|
for _, r := range rows {
|
||||||
|
chats = append(chats, model.Chat{
|
||||||
|
ID: r.ID,
|
||||||
|
Title: r.Title,
|
||||||
|
CreatedAt: r.CreatedAt,
|
||||||
|
MemberIDs: r.MemberIds,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
decoded, derr := decodeCursor(*cursor, uuid.Nil)
|
||||||
|
if derr != nil {
|
||||||
return nil, nil, ErrInvalidCursor
|
return nil, nil, ErrInvalidCursor
|
||||||
}
|
}
|
||||||
|
|
||||||
afterCreatedAt = &decoded.CreatedAt
|
rows, err := s.q.ListChatsAfter(ctx, db.ListChatsAfterParams{
|
||||||
afterID = &decoded.ID
|
UserID: userID,
|
||||||
}
|
AfterCreatedAt: decoded.CreatedAt,
|
||||||
|
AfterID: decoded.ID,
|
||||||
rows, err := s.q.ListChats(ctx, db.ListChatsParams{
|
Lim: int32(limit + 1),
|
||||||
UserID: userID,
|
|
||||||
AfterCreatedAt: afterCreatedAt,
|
|
||||||
AfterID: afterID,
|
|
||||||
Lim: int32(limit + 1),
|
|
||||||
})
|
|
||||||
if err != nil {
|
|
||||||
return nil, nil, err
|
|
||||||
}
|
|
||||||
|
|
||||||
hasMore := len(rows) > limit
|
|
||||||
if hasMore {
|
|
||||||
rows = rows[:limit]
|
|
||||||
}
|
|
||||||
|
|
||||||
chats := make([]model.Chat, 0, len(rows))
|
|
||||||
for _, r := range rows {
|
|
||||||
chats = append(chats, model.Chat{
|
|
||||||
ID: r.ID,
|
|
||||||
Title: r.Title,
|
|
||||||
CreatedAt: r.CreatedAt,
|
|
||||||
MemberIDs: r.MemberIds,
|
|
||||||
})
|
})
|
||||||
|
if err != nil {
|
||||||
|
return nil, nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
chats = make([]model.Chat, 0, len(rows))
|
||||||
|
for _, r := range rows {
|
||||||
|
chats = append(chats, model.Chat{
|
||||||
|
ID: r.ID,
|
||||||
|
Title: r.Title,
|
||||||
|
CreatedAt: r.CreatedAt,
|
||||||
|
MemberIDs: r.MemberIds,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
hasMore := len(chats) > limit
|
||||||
|
if hasMore {
|
||||||
|
chats = chats[:limit]
|
||||||
}
|
}
|
||||||
|
|
||||||
var next *string
|
var next *string
|
||||||
if hasMore {
|
if hasMore {
|
||||||
last := chats[len(chats)-1]
|
last := chats[len(chats)-1]
|
||||||
|
|
||||||
c := encodeCursor(Cursor{
|
c := encodeCursor(Cursor{
|
||||||
CreatedAt: last.CreatedAt,
|
CreatedAt: last.CreatedAt,
|
||||||
ID: last.ID,
|
ID: last.ID,
|
||||||
|
|||||||
+17
-16
@@ -3,7 +3,6 @@ package service
|
|||||||
import (
|
import (
|
||||||
"context"
|
"context"
|
||||||
"errors"
|
"errors"
|
||||||
"time"
|
|
||||||
|
|
||||||
"github.com/google/uuid"
|
"github.com/google/uuid"
|
||||||
|
|
||||||
@@ -17,7 +16,8 @@ var ErrMessageChatNotFound = errors.New("chat not found")
|
|||||||
type messageQueries interface {
|
type messageQueries interface {
|
||||||
CreateMessage(ctx context.Context, arg db.CreateMessageParams) (db.Message, error)
|
CreateMessage(ctx context.Context, arg db.CreateMessageParams) (db.Message, error)
|
||||||
IsChatMember(ctx context.Context, arg db.IsChatMemberParams) (bool, error)
|
IsChatMember(ctx context.Context, arg db.IsChatMemberParams) (bool, error)
|
||||||
ListMessages(ctx context.Context, arg db.ListMessagesParams) ([]db.Message, error)
|
ListMessagesAfter(ctx context.Context, arg db.ListMessagesAfterParams) ([]db.Message, error)
|
||||||
|
ListMessagesFirstPage(ctx context.Context, arg db.ListMessagesFirstPageParams) ([]db.Message, error)
|
||||||
}
|
}
|
||||||
|
|
||||||
type MessageService struct {
|
type MessageService struct {
|
||||||
@@ -79,25 +79,26 @@ func (s *MessageService) List(
|
|||||||
return nil, nil, ErrMessageChatNotFound
|
return nil, nil, ErrMessageChatNotFound
|
||||||
}
|
}
|
||||||
|
|
||||||
var afterCreatedAt *time.Time
|
var rows []db.Message
|
||||||
var afterID *uuid.UUID
|
|
||||||
|
|
||||||
if cursor != nil {
|
if cursor == nil {
|
||||||
decoded, err := decodeCursor(*cursor, chatID)
|
rows, err = s.q.ListMessagesFirstPage(ctx, db.ListMessagesFirstPageParams{
|
||||||
if err != nil {
|
ChatID: chatID,
|
||||||
|
Lim: int32(limit + 1),
|
||||||
|
})
|
||||||
|
} else {
|
||||||
|
decoded, derr := decodeCursor(*cursor, chatID)
|
||||||
|
if derr != nil {
|
||||||
return nil, nil, ErrInvalidCursor
|
return nil, nil, ErrInvalidCursor
|
||||||
}
|
}
|
||||||
|
|
||||||
afterCreatedAt = &decoded.CreatedAt
|
rows, err = s.q.ListMessagesAfter(ctx, db.ListMessagesAfterParams{
|
||||||
afterID = &decoded.ID
|
ChatID: chatID,
|
||||||
|
AfterCreatedAt: decoded.CreatedAt,
|
||||||
|
AfterID: decoded.ID,
|
||||||
|
Lim: int32(limit + 1),
|
||||||
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
rows, err := s.q.ListMessages(ctx, db.ListMessagesParams{
|
|
||||||
ChatID: chatID,
|
|
||||||
AfterCreatedAt: afterCreatedAt,
|
|
||||||
AfterID: afterID,
|
|
||||||
Lim: int32(limit + 1),
|
|
||||||
})
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, nil, err
|
return nil, nil, err
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,236 +0,0 @@
|
|||||||
package store
|
|
||||||
|
|
||||||
import (
|
|
||||||
"errors"
|
|
||||||
"slices"
|
|
||||||
"sort"
|
|
||||||
"sync"
|
|
||||||
"time"
|
|
||||||
|
|
||||||
"github.com/google/uuid"
|
|
||||||
|
|
||||||
"mtusi2026-messenger/internal/model"
|
|
||||||
)
|
|
||||||
|
|
||||||
var (
|
|
||||||
ErrNotFound = errors.New("not found")
|
|
||||||
ErrConflict = errors.New("conflict")
|
|
||||||
ErrDuplicateMember = errors.New("duplicate member id")
|
|
||||||
ErrUnknownMember = errors.New("unknown member id")
|
|
||||||
ErrInvalidCursor = errors.New("invalid cursor")
|
|
||||||
)
|
|
||||||
|
|
||||||
type Memory struct {
|
|
||||||
mu sync.RWMutex
|
|
||||||
|
|
||||||
users map[uuid.UUID]model.User
|
|
||||||
usersByUsername map[string]uuid.UUID
|
|
||||||
chats map[uuid.UUID]model.Chat
|
|
||||||
messages map[uuid.UUID]model.Message
|
|
||||||
chatMessages map[uuid.UUID][]uuid.UUID
|
|
||||||
}
|
|
||||||
|
|
||||||
func New() *Memory {
|
|
||||||
return &Memory{
|
|
||||||
users: make(map[uuid.UUID]model.User),
|
|
||||||
usersByUsername: make(map[string]uuid.UUID),
|
|
||||||
chats: make(map[uuid.UUID]model.Chat),
|
|
||||||
messages: make(map[uuid.UUID]model.Message),
|
|
||||||
chatMessages: make(map[uuid.UUID][]uuid.UUID),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func (m *Memory) CreateUser(username, displayName string) (model.User, error) {
|
|
||||||
m.mu.Lock()
|
|
||||||
defer m.mu.Unlock()
|
|
||||||
|
|
||||||
if _, exists := m.usersByUsername[username]; exists {
|
|
||||||
return model.User{}, ErrConflict
|
|
||||||
}
|
|
||||||
|
|
||||||
user := model.User{
|
|
||||||
ID: uuid.New(),
|
|
||||||
Username: username,
|
|
||||||
DisplayName: displayName,
|
|
||||||
CreatedAt: time.Now().UTC(),
|
|
||||||
}
|
|
||||||
|
|
||||||
m.users[user.ID] = user
|
|
||||||
m.usersByUsername[user.Username] = user.ID
|
|
||||||
|
|
||||||
return user, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func (m *Memory) GetUser(id uuid.UUID) (model.User, error) {
|
|
||||||
m.mu.RLock()
|
|
||||||
defer m.mu.RUnlock()
|
|
||||||
|
|
||||||
user, exists := m.users[id]
|
|
||||||
if !exists {
|
|
||||||
return model.User{}, ErrNotFound
|
|
||||||
}
|
|
||||||
|
|
||||||
return user, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func (m *Memory) CreateChat(title string, memberIDs []uuid.UUID) (model.Chat, error) {
|
|
||||||
m.mu.Lock()
|
|
||||||
defer m.mu.Unlock()
|
|
||||||
|
|
||||||
seen := make(map[uuid.UUID]struct{}, len(memberIDs))
|
|
||||||
for _, id := range memberIDs {
|
|
||||||
if _, dup := seen[id]; dup {
|
|
||||||
return model.Chat{}, ErrDuplicateMember
|
|
||||||
}
|
|
||||||
seen[id] = struct{}{}
|
|
||||||
|
|
||||||
if _, exists := m.users[id]; !exists {
|
|
||||||
return model.Chat{}, ErrUnknownMember
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
chat := model.Chat{
|
|
||||||
ID: uuid.New(),
|
|
||||||
Title: title,
|
|
||||||
MemberIDs: append([]uuid.UUID(nil), memberIDs...),
|
|
||||||
CreatedAt: time.Now().UTC(),
|
|
||||||
}
|
|
||||||
|
|
||||||
m.chats[chat.ID] = chat
|
|
||||||
|
|
||||||
return chat, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func (m *Memory) GetChat(id uuid.UUID, userID uuid.UUID) (model.Chat, error) {
|
|
||||||
m.mu.RLock()
|
|
||||||
defer m.mu.RUnlock()
|
|
||||||
|
|
||||||
chat, exists := m.chats[id]
|
|
||||||
if !exists || !slices.Contains(chat.MemberIDs, userID) {
|
|
||||||
return model.Chat{}, ErrNotFound
|
|
||||||
}
|
|
||||||
|
|
||||||
chat.MemberIDs = append([]uuid.UUID(nil), chat.MemberIDs...)
|
|
||||||
|
|
||||||
return chat, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func (m *Memory) ListChats(
|
|
||||||
userID uuid.UUID,
|
|
||||||
afterCreatedAt *time.Time,
|
|
||||||
afterID *uuid.UUID,
|
|
||||||
limit int,
|
|
||||||
) ([]model.Chat, bool, error) {
|
|
||||||
m.mu.RLock()
|
|
||||||
defer m.mu.RUnlock()
|
|
||||||
|
|
||||||
chats := make([]model.Chat, 0)
|
|
||||||
for _, c := range m.chats {
|
|
||||||
if slices.Contains(c.MemberIDs, userID) {
|
|
||||||
c.MemberIDs = append([]uuid.UUID(nil), c.MemberIDs...)
|
|
||||||
chats = append(chats, c)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
sort.Slice(chats, func(i, j int) bool {
|
|
||||||
if !chats[i].CreatedAt.Equal(chats[j].CreatedAt) {
|
|
||||||
return chats[i].CreatedAt.Before(chats[j].CreatedAt)
|
|
||||||
}
|
|
||||||
return chats[i].ID.String() < chats[j].ID.String()
|
|
||||||
})
|
|
||||||
|
|
||||||
start := 0
|
|
||||||
if afterCreatedAt != nil && afterID != nil {
|
|
||||||
start = sort.Search(len(chats), func(i int) bool {
|
|
||||||
chat := chats[i]
|
|
||||||
|
|
||||||
return chat.CreatedAt.After(*afterCreatedAt) ||
|
|
||||||
(chat.CreatedAt.Equal(*afterCreatedAt) &&
|
|
||||||
chat.ID.String() > afterID.String())
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
end := start + limit
|
|
||||||
hasMore := end < len(chats)
|
|
||||||
if end > len(chats) {
|
|
||||||
end = len(chats)
|
|
||||||
}
|
|
||||||
|
|
||||||
return chats[start:end], hasMore, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func (m *Memory) CreateMessage(
|
|
||||||
chatID uuid.UUID,
|
|
||||||
senderID uuid.UUID,
|
|
||||||
text string,
|
|
||||||
) (model.Message, error) {
|
|
||||||
m.mu.Lock()
|
|
||||||
defer m.mu.Unlock()
|
|
||||||
|
|
||||||
chat, exists := m.chats[chatID]
|
|
||||||
if !exists || !slices.Contains(chat.MemberIDs, senderID) {
|
|
||||||
return model.Message{}, ErrNotFound
|
|
||||||
}
|
|
||||||
|
|
||||||
message := model.Message{
|
|
||||||
ID: uuid.New(),
|
|
||||||
ChatID: chatID,
|
|
||||||
SenderID: senderID,
|
|
||||||
Text: text,
|
|
||||||
CreatedAt: time.Now().UTC(),
|
|
||||||
}
|
|
||||||
|
|
||||||
m.messages[message.ID] = message
|
|
||||||
m.chatMessages[chatID] = append(m.chatMessages[chatID], message.ID)
|
|
||||||
|
|
||||||
return message, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func (m *Memory) ListMessages(
|
|
||||||
chatID uuid.UUID,
|
|
||||||
userID uuid.UUID,
|
|
||||||
afterCreatedAt *time.Time,
|
|
||||||
afterID *uuid.UUID,
|
|
||||||
limit int,
|
|
||||||
) ([]model.Message, bool, error) {
|
|
||||||
m.mu.RLock()
|
|
||||||
defer m.mu.RUnlock()
|
|
||||||
|
|
||||||
chat, exists := m.chats[chatID]
|
|
||||||
if !exists || !slices.Contains(chat.MemberIDs, userID) {
|
|
||||||
return nil, false, ErrNotFound
|
|
||||||
}
|
|
||||||
|
|
||||||
ids := m.chatMessages[chatID]
|
|
||||||
messages := make([]model.Message, 0, len(ids))
|
|
||||||
|
|
||||||
for _, id := range ids {
|
|
||||||
messages = append(messages, m.messages[id])
|
|
||||||
}
|
|
||||||
|
|
||||||
sort.Slice(messages, func(i, j int) bool {
|
|
||||||
if !messages[i].CreatedAt.Equal(messages[j].CreatedAt) {
|
|
||||||
return messages[i].CreatedAt.Before(messages[j].CreatedAt)
|
|
||||||
}
|
|
||||||
return messages[i].ID.String() < messages[j].ID.String()
|
|
||||||
})
|
|
||||||
|
|
||||||
start := 0
|
|
||||||
if afterCreatedAt != nil && afterID != nil {
|
|
||||||
start = sort.Search(len(messages), func(i int) bool {
|
|
||||||
msg := messages[i]
|
|
||||||
|
|
||||||
return msg.CreatedAt.After(*afterCreatedAt) ||
|
|
||||||
(msg.CreatedAt.Equal(*afterCreatedAt) &&
|
|
||||||
msg.ID.String() > afterID.String())
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
end := start + limit
|
|
||||||
hasMore := end < len(messages)
|
|
||||||
if end > len(messages) {
|
|
||||||
end = len(messages)
|
|
||||||
}
|
|
||||||
|
|
||||||
return messages[start:end], hasMore, nil
|
|
||||||
}
|
|
||||||
@@ -0,0 +1,89 @@
|
|||||||
|
//go:build failure
|
||||||
|
|
||||||
|
package studenttests_test
|
||||||
|
|
||||||
|
import (
|
||||||
|
"net/http"
|
||||||
|
"os/exec"
|
||||||
|
"testing"
|
||||||
|
"time"
|
||||||
|
)
|
||||||
|
|
||||||
|
func compose(t *testing.T, args ...string) {
|
||||||
|
t.Helper()
|
||||||
|
|
||||||
|
cmd := exec.Command("docker", append([]string{"compose"}, args...)...)
|
||||||
|
cmd.Dir = ".."
|
||||||
|
if out, err := cmd.CombinedOutput(); err != nil {
|
||||||
|
t.Fatalf("docker compose %v: %v\n%s", args, err, out)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func stopService(t *testing.T, name string) {
|
||||||
|
t.Helper()
|
||||||
|
|
||||||
|
compose(t, "stop", name)
|
||||||
|
t.Cleanup(func() {
|
||||||
|
compose(t, "start", name)
|
||||||
|
waitReady(t)
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
func waitReady(t *testing.T) {
|
||||||
|
t.Helper()
|
||||||
|
|
||||||
|
deadline := time.Now().Add(60 * time.Second)
|
||||||
|
for time.Now().Before(deadline) {
|
||||||
|
resp, err := httpClient.Get(*baseURL + "/health/ready")
|
||||||
|
if err == nil {
|
||||||
|
resp.Body.Close()
|
||||||
|
if resp.StatusCode == http.StatusOK {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
}
|
||||||
|
time.Sleep(500 * time.Millisecond)
|
||||||
|
}
|
||||||
|
t.Fatal("service did not become ready in 60s")
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestRedisDown(t *testing.T) {
|
||||||
|
user := createUser(t)
|
||||||
|
|
||||||
|
stopService(t, "redis")
|
||||||
|
|
||||||
|
// настоящий токен
|
||||||
|
resp := doRequest(t, http.MethodGet, "/api/v1/users/me", user.Token, nil)
|
||||||
|
requireStatus(t, resp, http.StatusOK)
|
||||||
|
resp.Body.Close()
|
||||||
|
|
||||||
|
// выдуманный токен
|
||||||
|
resp = doRequest(t, http.MethodGet, "/api/v1/users/me", "forged-"+user.Token, nil)
|
||||||
|
requireStatus(t, resp, http.StatusUnauthorized)
|
||||||
|
resp.Body.Close()
|
||||||
|
|
||||||
|
// без токена
|
||||||
|
resp = doRequest(t, http.MethodGet, "/api/v1/users/me", "", nil)
|
||||||
|
requireStatus(t, resp, http.StatusUnauthorized)
|
||||||
|
resp.Body.Close()
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestDatabaseDown(t *testing.T) {
|
||||||
|
user := createUser(t) // токен ещё не использован, ключа в Redis нет
|
||||||
|
|
||||||
|
stopService(t, "postgres")
|
||||||
|
|
||||||
|
// ключа в кэше нет, проверить сессию негде
|
||||||
|
resp := doRequest(t, http.MethodGet, "/api/v1/users/me", user.Token, nil)
|
||||||
|
requireStatus(t, resp, http.StatusServiceUnavailable)
|
||||||
|
resp.Body.Close()
|
||||||
|
|
||||||
|
// выдуманный токен
|
||||||
|
resp = doRequest(t, http.MethodGet, "/api/v1/users/me", "forged-"+user.Token, nil)
|
||||||
|
requireStatus(t, resp, http.StatusServiceUnavailable)
|
||||||
|
resp.Body.Close()
|
||||||
|
|
||||||
|
// без токена
|
||||||
|
resp = doRequest(t, http.MethodGet, "/api/v1/users/me", "", nil)
|
||||||
|
requireStatus(t, resp, http.StatusUnauthorized)
|
||||||
|
resp.Body.Close()
|
||||||
|
}
|
||||||
@@ -0,0 +1,42 @@
|
|||||||
|
//go:build failure
|
||||||
|
|
||||||
|
package studenttests_test
|
||||||
|
|
||||||
|
import (
|
||||||
|
"net/http"
|
||||||
|
"os/exec"
|
||||||
|
"testing"
|
||||||
|
"time"
|
||||||
|
)
|
||||||
|
|
||||||
|
const shortTTLContainer = "api-short-ttl"
|
||||||
|
const shortTTLURL = "http://localhost:8081"
|
||||||
|
|
||||||
|
func TestSessionExpiry(t *testing.T) {
|
||||||
|
_ = exec.Command("docker", "rm", "-f", shortTTLContainer).Run()
|
||||||
|
|
||||||
|
compose(t, "run", "-d", "--no-deps", "--name", shortTTLContainer,
|
||||||
|
"-e", "SESSION_TTL_SECONDS=3",
|
||||||
|
"-p", "127.0.0.1:8081:8080", "api")
|
||||||
|
t.Cleanup(func() {
|
||||||
|
_ = exec.Command("docker", "rm", "-f", shortTTLContainer).Run()
|
||||||
|
})
|
||||||
|
|
||||||
|
old := *baseURL
|
||||||
|
*baseURL = shortTTLURL
|
||||||
|
t.Cleanup(func() { *baseURL = old })
|
||||||
|
|
||||||
|
waitReady(t)
|
||||||
|
|
||||||
|
user := createUser(t)
|
||||||
|
|
||||||
|
resp := doRequest(t, http.MethodGet, "/api/v1/users/me", user.Token, nil)
|
||||||
|
requireStatus(t, resp, http.StatusOK)
|
||||||
|
resp.Body.Close()
|
||||||
|
|
||||||
|
time.Sleep(4 * time.Second)
|
||||||
|
|
||||||
|
resp = doRequest(t, http.MethodGet, "/api/v1/users/me", user.Token, nil)
|
||||||
|
requireStatus(t, resp, http.StatusUnauthorized)
|
||||||
|
resp.Body.Close()
|
||||||
|
}
|
||||||
+8
-2
@@ -2,10 +2,13 @@ LOAD_ARGS = $(if $(LOAD_WORKERS),-workers=$(LOAD_WORKERS),) \
|
|||||||
$(if $(LOAD_DURATION),-duration=$(LOAD_DURATION),) \
|
$(if $(LOAD_DURATION),-duration=$(LOAD_DURATION),) \
|
||||||
$(if $(LOAD_RATE),-rate=$(LOAD_RATE),)
|
$(if $(LOAD_RATE),-rate=$(LOAD_RATE),)
|
||||||
|
|
||||||
.PHONY: help-go contract-go race-go load-go
|
.PHONY: help-go contract-go race-go load-go failure-go
|
||||||
|
|
||||||
help-go:
|
help-go:
|
||||||
@echo "contract-go: student contract tests; race-go: concurrency test with -race; load-go: Go load test"
|
@echo "contract-go: contract tests"
|
||||||
|
@echo "race-go: concurrency tests (-race)"
|
||||||
|
@echo "load-go: load test"
|
||||||
|
@echo "failure-go: dependency failure tests (stops redis/postgres containers)"
|
||||||
|
|
||||||
contract-go:
|
contract-go:
|
||||||
go test -tags=contract ./student-tests/... -v -args -base-url=$(BASE_URL)
|
go test -tags=contract ./student-tests/... -v -args -base-url=$(BASE_URL)
|
||||||
@@ -15,3 +18,6 @@ race-go:
|
|||||||
|
|
||||||
load-go:
|
load-go:
|
||||||
go test -tags=load ./student-tests/... -v -args -base-url=$(BASE_URL) $(LOAD_ARGS)
|
go test -tags=load ./student-tests/... -v -args -base-url=$(BASE_URL) $(LOAD_ARGS)
|
||||||
|
|
||||||
|
failure-go:
|
||||||
|
go test -tags=failure ./student-tests/... -v -args -base-url=$(BASE_URL)
|
||||||
|
|||||||
Reference in New Issue
Block a user