Исправить замечания ревью: restart API, JSON, текст, deps, restore.
Skeleton contracts / contracts (pull_request) Canceled after 0s
Skeleton contracts / contracts (pull_request) Canceled after 0s
Hook теперь реально перезапускает api; хвост JSON и тело login отклоняются; текст сообщений сохраняется целиком; отказы deps проверяются assert-ами; pg_restore замеряется.
This commit is contained in:
@@ -56,9 +56,10 @@ bash scripts/run_track2.sh
|
||||
| Откат создания чата | неизвестный участник | 400, строк с этим title: 0 | `evidence/student-test.txt` |
|
||||
| Неверный пароль, logout, X-User-Id, Basic на /users/me | student-test | 401, после logout повторный DELETE тоже 401 | `evidence/student-test.txt` |
|
||||
| Короткий TTL | `SESSION_TTL=2s`, пауза 2.5 с | 401 | `evidence/student-test.txt` |
|
||||
| Redis/Postgres недоступны | `scripts/check_deps.sh` и закрытый клиент Redis | `/health/ready` = 503, Bearer не становится 200; после start снова 200 | `evidence/deps-down.txt`, `evidence/student-test.txt` |
|
||||
| Redis/Postgres недоступны | `bash scripts/check_deps.sh` (assert + Bearer) и Go-тесты closed Redis/Postgres | ready/me = 503 при отказе, 200 после восстановления; без тела пользователя | `evidence/deps-down.txt`, `evidence/student-test.txt` |
|
||||
| Хвост JSON / текст / тело сессии | student-test | `{"text":"valid"}}` → 400; пробелы сохранены; тело на login → 400 | `evidence/student-test.txt` |
|
||||
| EXPLAIN на большой истории | трек 2, чат 74449 сообщений | см. ниже | `evidence/track2/` |
|
||||
| Backup и сверка | `pg_dump -Fc` → новая база | 100000 сообщений, checksum совпал | `evidence/track2/restore.json` |
|
||||
| Backup и сверка | `pg_dump -Fc` → `pg_restore` в новую базу | 100000 сообщений, checksum совпал; замер restore в timing | `evidence/track2/restore.json`, `evidence/track2/restore_timing.json` |
|
||||
|
||||
`scripts/restart.sh` перезапускает postgres, redis и api и не вызывает `down -v`. До и после прогона контейнеры — `mtusi2026lab2-api-1`, `mtusi2026lab2-postgres-1`, `mtusi2026lab2-redis-1`.
|
||||
|
||||
@@ -81,12 +82,14 @@ bash scripts/run_track2.sh
|
||||
|
||||
**Восстановление.** Counts и checksum совпали, 100000 = 100000. Дамп снят после COMMIT загрузки, поэтому сверка не показывает потерю незафиксированных строк. `appendfsync everysec` у Redis к этому дампу не относится: в дампе только PostgreSQL.
|
||||
|
||||
**Замер `pg_restore`.** Граница: wall clock только вокруг `docker compose exec … pg_restore` в уже созданную пустую `track2_restore` (после `DROP`/`CREATE`), до checksum-verify. Не включает prepare/explain/`pg_dump`. Число пишется в `evidence/track2/restore_timing.json` скриптом `scripts/run_track2.sh`.
|
||||
|
||||
| Воздействие | Что ожидаем | Что наблюдали | Время восстановления / потеря данных |
|
||||
| --- | --- | --- | --- |
|
||||
| `scripts/restart.sh` | те же сообщения и тот же токен | PASS persistence | API дождался Postgres и поднялся в пределах 90 с теста; подтверждённые строки на месте |
|
||||
| `docker compose stop redis` | `/health/ready` 503, не анонимный 200 | 503, затем 200 | около секунды после start |
|
||||
| `docker compose stop postgres` | то же для БД | 503, затем 200 | около секунды после start |
|
||||
| `pg_restore` в новую базу | те же 100000 строк | checksum совпал | дамп консистентен на момент `pg_dump`; незакоммиченное не входило |
|
||||
| `scripts/restart.sh` | рестарт api+postgres+redis; те же сообщения и токен | PASS persistence; меняются StartedAt/PID всех трёх | API ждёт Postgres до 45 с при старте; подтверждённые строки на месте |
|
||||
| `scripts/check_deps.sh` (redis) | ready/me → 503, затем 200 | PASS со assert | восстановление ready ≤30 с |
|
||||
| `scripts/check_deps.sh` (postgres) | то же для БД | PASS со assert | восстановление ready ≤30 с |
|
||||
| `pg_restore` в новую базу | те же 100000 строк | checksum совпал | **1.256 s** (`evidence/track2/restore_timing.json`); граница — только `pg_restore` |
|
||||
|
||||
## Ограничения и следующие шаги
|
||||
|
||||
|
||||
+21
-5
@@ -1,9 +1,25 @@
|
||||
ready_before=200
|
||||
register=201 (want 201)
|
||||
login=201 (want 201)
|
||||
ready_before=200 (want 200)
|
||||
me_before=200 (want 200)
|
||||
stop redis
|
||||
ready_redis_down=503
|
||||
Container mtusi2026lab2-redis-1 Stopping
|
||||
Container mtusi2026lab2-redis-1 Stopped
|
||||
ready_redis_down=503 (want 503)
|
||||
me_redis_down=503 (want 503)
|
||||
start redis
|
||||
ready_redis_back=200
|
||||
Container mtusi2026lab2-redis-1 Starting
|
||||
Container mtusi2026lab2-redis-1 Started
|
||||
ready_redis_back=200 (want 200)
|
||||
me_redis_back=200 (want 200)
|
||||
stop postgres
|
||||
ready_postgres_down=503
|
||||
Container mtusi2026lab2-postgres-1 Stopping
|
||||
Container mtusi2026lab2-postgres-1 Stopped
|
||||
ready_postgres_down=503 (want 503)
|
||||
me_postgres_down=503 (want 503)
|
||||
start postgres
|
||||
ready_postgres_back=200
|
||||
Container mtusi2026lab2-postgres-1 Starting
|
||||
Container mtusi2026lab2-postgres-1 Started
|
||||
ready_postgres_back=200 (want 200)
|
||||
me_postgres_back=200 (want 200)
|
||||
PASS: dependency outages return 503 and recover
|
||||
|
||||
@@ -0,0 +1,8 @@
|
||||
=== before restart hook ===
|
||||
/mtusi2026lab2-api-1 pid=95417 started=2026-10-29T17:47:34.473859844Z
|
||||
/mtusi2026lab2-postgres-1 pid=19189 started=2026-10-14T19:45:49.087666417Z
|
||||
/mtusi2026lab2-redis-1 pid=19035 started=2026-10-14T19:45:47.177549916Z
|
||||
=== after restart hook ===
|
||||
/mtusi2026lab2-api-1 pid=95905 started=2026-10-29T17:48:00.300560134Z
|
||||
/mtusi2026lab2-postgres-1 pid=95992 started=2026-10-29T17:48:00.441077842Z
|
||||
/mtusi2026lab2-redis-1 pid=95960 started=2026-10-29T17:48:00.393825134Z
|
||||
+134
-95
@@ -1,106 +1,145 @@
|
||||
go test ./student-tests/ -v -count=1 -timeout 180s
|
||||
=== RUN TestMalformedJSONAndValidation
|
||||
api_test.go:73: → битый JSON, лишнее поле, пустой текст, чужой чат
|
||||
2026/10/14 22:42:40 method=POST path=/api/v1/users status=400 request_id=db0c2117-db67-4ab9-a699-15677c5c8e82 duration_ms=0
|
||||
api_test.go:76: status=400 body={"error":{"code":"invalid_request","message":"malformed json","request_id":"db0c2117-db67-4ab9-a699-15677c5c8e82"}}
|
||||
2026/10/14 22:42:40 method=POST path=/api/v1/users status=400 request_id=e9462332-69fc-4af0-b565-138cdb4de77c duration_ms=0
|
||||
api_test.go:83: status=400 body={"error":{"code":"invalid_request","message":"malformed json","request_id":"e9462332-69fc-4af0-b565-138cdb4de77c"}}
|
||||
2026/10/14 22:42:40 method=POST path=/api/v1/users status=201 request_id=2c9326a6-18dd-48f2-81d4-25649f6576ba duration_ms=47
|
||||
api_test.go:88: создан ok_user_3cadde8f id=651a935f-d2c3-43c1-8a41-2091d51869df
|
||||
2026/10/14 22:42:40 method=POST path=/api/v1/auth/sessions status=201 request_id=dac3bb08-334d-464b-a77e-7e0caa05da79 duration_ms=43
|
||||
api_test.go:73: → битый JSON, хвост после объекта, лишнее поле, пустой текст, чужой чат
|
||||
2026/10/29 20:47:44 method=POST path=/api/v1/users status=400 request_id=07ffb582-cb1f-4ef5-9e11-2fbb878427b4 duration_ms=0
|
||||
api_test.go:76: status=400 body={"error":{"code":"invalid_request","message":"malformed json","request_id":"07ffb582-cb1f-4ef5-9e11-2fbb878427b4"}}
|
||||
2026/10/29 20:47:44 method=POST path=/api/v1/users status=400 request_id=63ec9aa4-2e2b-4cfe-83bd-55ab292f4e9d duration_ms=0
|
||||
api_test.go:83: status=400 body={"error":{"code":"invalid_request","message":"malformed json","request_id":"63ec9aa4-2e2b-4cfe-83bd-55ab292f4e9d"}}
|
||||
2026/10/29 20:47:44 method=POST path=/api/v1/users status=201 request_id=5daec559-c208-4ad8-a62b-a6c3d6325224 duration_ms=61
|
||||
api_test.go:88: создан ok_user_d13ec4d2 id=4f39f96a-47c7-441a-a7b2-ab3c18c5238a
|
||||
2026/10/29 20:47:44 method=POST path=/api/v1/auth/sessions status=201 request_id=6188dae9-fc0f-4411-a1e0-5b7ea9be9be8 duration_ms=57
|
||||
api_test.go:89: сессия выпущена, длина токена=64 (значение не печатаем)
|
||||
2026/10/14 22:42:40 method=POST path=/api/v1/chats status=201 request_id=d27a6905-9e2e-4401-bcde-d193fd3ffd31 duration_ms=8
|
||||
2026/10/14 22:42:40 method=POST path=/api/v1/chats/72b3d41a-2a9b-4200-89c7-04b8cf677fbd/messages status=400 request_id=1ab2e48a-039f-47b6-b10c-9db395a19c08 duration_ms=0
|
||||
api_test.go:92: status=400 body={"error":{"code":"invalid_request","message":"invalid text","request_id":"1ab2e48a-039f-47b6-b10c-9db395a19c08"}}
|
||||
2026/10/14 22:42:40 method=POST path=/api/v1/users status=201 request_id=39d6f236-ef73-47ba-83cd-2b364cad2e93 duration_ms=41
|
||||
api_test.go:97: создан outsider_6da955f2 id=11dc7c58-8f82-4df6-9f21-efe30bbeca0b
|
||||
2026/10/14 22:42:40 method=POST path=/api/v1/auth/sessions status=201 request_id=83a59fc3-2092-4b62-bb99-d7c1b1bbf0d8 duration_ms=43
|
||||
api_test.go:98: сессия выпущена, длина токена=64 (значение не печатаем)
|
||||
2026/10/14 22:42:40 method=POST path=/api/v1/chats/72b3d41a-2a9b-4200-89c7-04b8cf677fbd/messages status=404 request_id=d010a434-6f1b-4755-af3a-e0ff70dd4977 duration_ms=2
|
||||
api_test.go:100: status=404 body={"error":{"code":"not_found","message":"object not found","request_id":"d010a434-6f1b-4755-af3a-e0ff70dd4977"}}
|
||||
api_test.go:104: ✓ валидация JSON, пустого текста и чужого чата
|
||||
--- PASS: TestMalformedJSONAndValidation (0.19s)
|
||||
2026/10/29 20:47:44 method=POST path=/api/v1/chats status=201 request_id=31a7e276-f96a-4f68-90c3-76a1bd276f05 duration_ms=10
|
||||
2026/10/29 20:47:44 method=POST path=/api/v1/chats/42e078e9-8ff3-43af-b8c6-00bd946b543c/messages status=400 request_id=95e3aea8-c57f-4c9f-bfa2-115ca7d2b498 duration_ms=0
|
||||
api_test.go:96: status=400 body={"error":{"code":"invalid_request","message":"malformed json","request_id":"95e3aea8-c57f-4c9f-bfa2-115ca7d2b498"}}
|
||||
2026/10/29 20:47:44 method=POST path=/api/v1/chats/42e078e9-8ff3-43af-b8c6-00bd946b543c/messages status=400 request_id=cdb3e520-f80f-495a-9ce6-6c169045ff76 duration_ms=0
|
||||
api_test.go:96: status=400 body={"error":{"code":"invalid_request","message":"malformed json","request_id":"cdb3e520-f80f-495a-9ce6-6c169045ff76"}}
|
||||
2026/10/29 20:47:44 method=POST path=/api/v1/chats/42e078e9-8ff3-43af-b8c6-00bd946b543c/messages status=400 request_id=baf6708a-1e84-4f1e-84dd-e8669167255a duration_ms=0
|
||||
api_test.go:103: status=400 body={"error":{"code":"invalid_request","message":"invalid text","request_id":"baf6708a-1e84-4f1e-84dd-e8669167255a"}}
|
||||
2026/10/29 20:47:44 method=POST path=/api/v1/users status=201 request_id=e8f319ad-ae8d-47e4-ab97-5b4bc1c18752 duration_ms=58
|
||||
api_test.go:108: создан outsider_f4260f0a id=562193aa-013b-47d7-9e33-86d2566504b5
|
||||
2026/10/29 20:47:44 method=POST path=/api/v1/auth/sessions status=201 request_id=def8f0a8-d757-4886-b7fa-251dc5de9f93 duration_ms=82
|
||||
api_test.go:109: сессия выпущена, длина токена=64 (значение не печатаем)
|
||||
2026/10/29 20:47:44 method=POST path=/api/v1/chats/42e078e9-8ff3-43af-b8c6-00bd946b543c/messages status=404 request_id=75d8c438-0584-4975-86cd-4980a7a050e5 duration_ms=3
|
||||
api_test.go:111: status=404 body={"error":{"code":"not_found","message":"object not found","request_id":"75d8c438-0584-4975-86cd-4980a7a050e5"}}
|
||||
api_test.go:115: ✓ валидация JSON, хвоста, пустого текста и чужого чата
|
||||
--- PASS: TestMalformedJSONAndValidation (0.28s)
|
||||
=== RUN TestMessageTextPreservedAndLengthOnOriginal
|
||||
api_test.go:121: → пробелы по краям сохраняются; длина считается по исходному тексту
|
||||
2026/10/29 20:47:44 method=POST path=/api/v1/users status=201 request_id=aea19d71-920c-45af-9543-17ee4835e645 duration_ms=50
|
||||
api_test.go:122: создан text_user_b1e2fef6 id=cbfe10ec-5f8c-452c-86c1-04d648f65685
|
||||
2026/10/29 20:47:44 method=POST path=/api/v1/auth/sessions status=201 request_id=1da405ac-4d27-46ea-b723-f8a6470e68fb duration_ms=49
|
||||
api_test.go:123: сессия выпущена, длина токена=64 (значение не печатаем)
|
||||
2026/10/29 20:47:44 method=POST path=/api/v1/chats status=201 request_id=a25c7326-cee4-4e5d-bcf9-f85b3b6d6805 duration_ms=6
|
||||
2026/10/29 20:47:44 method=POST path=/api/v1/chats/c361fe30-29ad-457a-94a7-9bb390d1a33f/messages status=201 request_id=67a8814e-9875-46cd-bff9-c0c882a4056d duration_ms=4
|
||||
api_test.go:130: status=201 body={"chat_id":"c361fe30-29ad-457a-94a7-9bb390d1a33f","created_at":"2026-10-29T17:47:44.480Z","id":"a085353e-1d84-4b4b-ac26-00ba43395ae8","sender_id":"cbfe10ec-5f8c-452c-86c1-04d648f65685","text":" строка\nс пробелами "}
|
||||
2026/10/29 20:47:44 method=POST path=/api/v1/chats/c361fe30-29ad-457a-94a7-9bb390d1a33f/messages status=400 request_id=051dd835-500e-48af-b733-46df94574879 duration_ms=1
|
||||
api_test.go:142: status=400 body={"error":{"code":"invalid_request","message":"invalid text","request_id":"051dd835-500e-48af-b733-46df94574879"}}
|
||||
api_test.go:146: ✓ текст сохранён целиком, обход лимита через TrimSpace закрыт
|
||||
--- PASS: TestMessageTextPreservedAndLengthOnOriginal (0.12s)
|
||||
=== RUN TestSessionRejectsJSONBody
|
||||
api_test.go:152: → POST /auth/sessions с телом должен быть 400 даже при верном Basic
|
||||
2026/10/29 20:47:44 method=POST path=/api/v1/users status=201 request_id=41b20b01-bee1-41cb-b596-8c99c7110e5c duration_ms=48
|
||||
api_test.go:153: создан body_user_a62526cb id=65e9cf5a-85e5-4f77-8dda-a0a7faa2dfff
|
||||
2026/10/29 20:47:44 method=POST path=/api/v1/auth/sessions status=400 request_id=e9bfc110-d2d4-43ef-be68-799002cd8ab7 duration_ms=0
|
||||
api_test.go:157: status=400 body={"error":{"code":"invalid_request","message":"session create must not have a body","request_id":"e9bfc110-d2d4-43ef-be68-799002cd8ab7"}}
|
||||
api_test.go:161: ✓ вход без JSON body
|
||||
--- PASS: TestSessionRejectsJSONBody (0.06s)
|
||||
=== RUN TestWrongPasswordLogoutAndIgnoredUserHeader
|
||||
api_test.go:110: → неверный пароль, Basic на бизнес-методе, X-User-Id, logout
|
||||
2026/10/14 22:42:40 method=POST path=/api/v1/users status=201 request_id=94135aad-22c5-4efe-9e9c-7c186e4e882f duration_ms=41
|
||||
api_test.go:111: создан auth_user_eeb9bffa id=24709210-e37e-412a-a2c3-c6bc6d1d94a5
|
||||
2026/10/14 22:42:40 method=POST path=/api/v1/users status=201 request_id=eb2ab683-800d-4e27-83f9-6babb77fb78d duration_ms=43
|
||||
api_test.go:112: создан auth_other_28c87fd6 id=7ba5a8e8-7334-4d9a-adc6-f1838016ad23
|
||||
2026/10/14 22:42:40 method=POST path=/api/v1/auth/sessions status=401 request_id=af58975d-5c3d-4105-9e75-eceb8779c0d9 duration_ms=42
|
||||
api_test.go:117: status=401 body={"error":{"code":"unauthorized","message":"authentication required","request_id":"af58975d-5c3d-4105-9e75-eceb8779c0d9"}}
|
||||
2026/10/14 22:42:40 method=POST path=/api/v1/auth/sessions status=201 request_id=37ceb9c7-1cc0-4e5e-abf2-5b1db8619733 duration_ms=42
|
||||
api_test.go:122: сессия выпущена, длина токена=64 (значение не печатаем)
|
||||
2026/10/14 22:42:40 method=GET path=/api/v1/users/me status=401 request_id=03c49eb3-a35e-4c83-b8ea-3d18810ec773 duration_ms=0
|
||||
api_test.go:126: status=401 body={"error":{"code":"unauthorized","message":"authentication required","request_id":"03c49eb3-a35e-4c83-b8ea-3d18810ec773"}}
|
||||
2026/10/14 22:42:40 method=GET path=/api/v1/users/me status=401 request_id=55a150d9-208a-4347-a930-4ff11c5233eb duration_ms=0
|
||||
api_test.go:132: status=401 body={"error":{"code":"unauthorized","message":"authentication required","request_id":"55a150d9-208a-4347-a930-4ff11c5233eb"}}
|
||||
2026/10/14 22:42:40 method=GET path=/api/v1/users/me status=200 request_id=70af7739-36a1-4877-a66a-dbb6363f0218 duration_ms=1
|
||||
api_test.go:141: status=200 body={"created_at":"2026-10-14T19:42:40.597Z","display_name":"Студент","id":"24709210-e37e-412a-a2c3-c6bc6d1d94a5","username":"auth_user_eeb9bffa"}
|
||||
2026/10/14 22:42:40 method=DELETE path=/api/v1/auth/sessions/current status=204 request_id=6d8a5397-9d10-4b99-867c-ac14aceac351 duration_ms=1
|
||||
api_test.go:147: logout status=204
|
||||
2026/10/14 22:42:40 method=GET path=/api/v1/users/me status=401 request_id=c50a007a-5035-4e06-ab4a-af010d47f8c3 duration_ms=1
|
||||
2026/10/14 22:42:40 method=DELETE path=/api/v1/auth/sessions/current status=401 request_id=1c274613-aeb3-4378-a750-cc94bd18bee6 duration_ms=1
|
||||
api_test.go:159: ✓ пароль, заголовки и отзыв сессии
|
||||
--- PASS: TestWrongPasswordLogoutAndIgnoredUserHeader (0.18s)
|
||||
api_test.go:167: → неверный пароль, Basic на бизнес-методе, X-User-Id, logout
|
||||
2026/10/29 20:47:44 method=POST path=/api/v1/users status=201 request_id=bdcf29a7-da3d-47d5-acd6-379624031349 duration_ms=43
|
||||
api_test.go:168: создан auth_user_8ea61397 id=7f9088b3-e7d0-459f-b16e-c0cabb207ab3
|
||||
2026/10/29 20:47:44 method=POST path=/api/v1/users status=201 request_id=36e342e7-00d8-4298-8837-bfce0376acac duration_ms=45
|
||||
api_test.go:169: создан auth_other_c9f4edef id=ec8192bd-1877-418f-b728-d5c603533198
|
||||
2026/10/29 20:47:44 method=POST path=/api/v1/auth/sessions status=401 request_id=cc140915-2153-4e31-9f4e-d079ee216501 duration_ms=45
|
||||
api_test.go:174: status=401 body={"error":{"code":"unauthorized","message":"authentication required","request_id":"cc140915-2153-4e31-9f4e-d079ee216501"}}
|
||||
2026/10/29 20:47:44 method=POST path=/api/v1/auth/sessions status=201 request_id=c46c9cf3-8dcd-426c-bdd9-7eb4abeafce7 duration_ms=44
|
||||
api_test.go:179: сессия выпущена, длина токена=64 (значение не печатаем)
|
||||
2026/10/29 20:47:44 method=GET path=/api/v1/users/me status=401 request_id=653cb9d3-8634-4bb8-a3b3-ba3e65a9aacd duration_ms=0
|
||||
api_test.go:183: status=401 body={"error":{"code":"unauthorized","message":"authentication required","request_id":"653cb9d3-8634-4bb8-a3b3-ba3e65a9aacd"}}
|
||||
2026/10/29 20:47:44 method=GET path=/api/v1/users/me status=401 request_id=81958bc7-b1c3-450a-b5ab-86e1446ab071 duration_ms=0
|
||||
api_test.go:189: status=401 body={"error":{"code":"unauthorized","message":"authentication required","request_id":"81958bc7-b1c3-450a-b5ab-86e1446ab071"}}
|
||||
2026/10/29 20:47:44 method=GET path=/api/v1/users/me status=200 request_id=0883609c-a19a-4a08-98f4-cb10b5c19321 duration_ms=1
|
||||
api_test.go:198: status=200 body={"created_at":"2026-10-29T17:47:44.588Z","display_name":"Студент","id":"7f9088b3-e7d0-459f-b16e-c0cabb207ab3","username":"auth_user_8ea61397"}
|
||||
2026/10/29 20:47:44 method=DELETE path=/api/v1/auth/sessions/current status=204 request_id=a07c1944-77b3-40b9-8f24-3e31159ef4d2 duration_ms=1
|
||||
api_test.go:204: logout status=204
|
||||
2026/10/29 20:47:44 method=GET path=/api/v1/users/me status=401 request_id=8296a53e-ba74-4bf6-b3f0-7b2229286f67 duration_ms=0
|
||||
2026/10/29 20:47:44 method=DELETE path=/api/v1/auth/sessions/current status=401 request_id=94eebe51-e15f-4e07-ad0f-220d97a7a387 duration_ms=0
|
||||
api_test.go:216: ✓ пароль, заголовки и отзыв сессии
|
||||
--- PASS: TestWrongPasswordLogoutAndIgnoredUserHeader (0.19s)
|
||||
=== RUN TestSessionExpiry
|
||||
api_test.go:165: → SESSION_TTL=2s: тот же токен после паузы должен стать 401, TTL рестартом API не продлевается
|
||||
2026/10/14 22:42:40 method=POST path=/api/v1/users status=201 request_id=74b3345f-dec8-407a-80d9-278a1df89319 duration_ms=44
|
||||
api_test.go:166: создан ttl_user_6308467a id=be7334ea-1153-41f9-8047-1365cac6f5e4
|
||||
2026/10/14 22:42:40 method=POST path=/api/v1/auth/sessions status=201 request_id=dca5d965-9d6d-4615-bfc3-cbb2072da796 duration_ms=43
|
||||
api_test.go:167: сессия выпущена, длина токена=64 (значение не печатаем)
|
||||
2026/10/14 22:42:43 method=GET path=/api/v1/users/me status=401 request_id=48e0b70b-ccb6-43ad-a346-28994552a1ca duration_ms=2
|
||||
api_test.go:170: status=401 body={"error":{"code":"unauthorized","message":"authentication required","request_id":"48e0b70b-ccb6-43ad-a346-28994552a1ca"}}
|
||||
api_test.go:174: ✓ истёкшая сессия отклонена
|
||||
--- PASS: TestSessionExpiry (2.59s)
|
||||
api_test.go:222: → SESSION_TTL=2s: тот же токен после паузы должен стать 401, TTL рестартом API не продлевается
|
||||
2026/10/29 20:47:44 method=POST path=/api/v1/users status=201 request_id=ed64da0d-3ea7-4e37-a751-232ce03550f4 duration_ms=47
|
||||
api_test.go:223: создан ttl_user_0b2e85c8 id=ca18a0c2-c3bd-4d00-ac2d-44eb26b0922b
|
||||
2026/10/29 20:47:44 method=POST path=/api/v1/auth/sessions status=201 request_id=6c194733-5ff3-47b7-a7bc-ce66a959e354 duration_ms=47
|
||||
api_test.go:224: сессия выпущена, длина токена=64 (значение не печатаем)
|
||||
2026/10/29 20:47:47 method=GET path=/api/v1/users/me status=401 request_id=936a0b2b-d79a-4b29-b420-d512789f7acf duration_ms=4
|
||||
api_test.go:227: status=401 body={"error":{"code":"unauthorized","message":"authentication required","request_id":"936a0b2b-d79a-4b29-b420-d512789f7acf"}}
|
||||
api_test.go:231: ✓ истёкшая сессия отклонена
|
||||
--- PASS: TestSessionExpiry (2.61s)
|
||||
=== RUN TestDuplicateUsernameRace
|
||||
api_test.go:181: → 8 параллельных регистраций username=race_c93a2ca7
|
||||
2026/10/14 22:42:43 method=POST path=/api/v1/users status=201 request_id=55b47bef-3dbf-40b6-ae97-54baf81e83f5 duration_ms=69
|
||||
2026/10/14 22:42:43 method=POST path=/api/v1/users status=409 request_id=5e44a96e-1029-417c-9e3b-64f89d848e0b duration_ms=71
|
||||
2026/10/14 22:42:43 method=POST path=/api/v1/users status=409 request_id=889d648a-012e-45c9-844d-222238746315 duration_ms=71
|
||||
2026/10/14 22:42:43 method=POST path=/api/v1/users status=409 request_id=f90c40f9-b561-46bf-b1cd-0d9d9c210b1b duration_ms=72
|
||||
2026/10/14 22:42:43 method=POST path=/api/v1/users status=409 request_id=c2a836e7-ac2f-4d7a-9cbd-a5244a9cf1b1 duration_ms=78
|
||||
2026/10/14 22:42:43 method=POST path=/api/v1/users status=409 request_id=f857d038-d7af-4102-9049-215605ad1447 duration_ms=77
|
||||
2026/10/14 22:42:43 method=POST path=/api/v1/users status=409 request_id=88060523-0692-4030-894a-3ef49ec98a3c duration_ms=80
|
||||
2026/10/14 22:42:43 method=POST path=/api/v1/users status=409 request_id=65d31b3a-04c9-40b4-9972-9599633b56e0 duration_ms=88
|
||||
api_test.go:206: created=1 conflict=7
|
||||
api_test.go:210: ✓ UNIQUE username выдержал гонку
|
||||
--- PASS: TestDuplicateUsernameRace (0.10s)
|
||||
api_test.go:238: → 8 параллельных регистраций username=race_56543e7c
|
||||
2026/10/29 20:47:47 method=POST path=/api/v1/users status=201 request_id=1511601d-1ecf-4cf7-936d-0b2be146f7f8 duration_ms=125
|
||||
2026/10/29 20:47:47 method=POST path=/api/v1/users status=409 request_id=469bf308-d590-4f45-8053-343a49c30bc7 duration_ms=133
|
||||
2026/10/29 20:47:47 method=POST path=/api/v1/users status=409 request_id=6c28dd60-51d0-48df-98b9-302f0e309f50 duration_ms=134
|
||||
2026/10/29 20:47:47 method=POST path=/api/v1/users status=409 request_id=bde105bf-a5b9-449c-a25c-6cb281564d36 duration_ms=135
|
||||
2026/10/29 20:47:47 method=POST path=/api/v1/users status=409 request_id=7c16403a-9e1a-401f-a481-0de961b04973 duration_ms=134
|
||||
2026/10/29 20:47:47 method=POST path=/api/v1/users status=409 request_id=e9d8fc0a-948c-4551-b706-707f737ece66 duration_ms=140
|
||||
2026/10/29 20:47:47 method=POST path=/api/v1/users status=409 request_id=16a48972-7bd0-44de-9763-998afa75df36 duration_ms=146
|
||||
2026/10/29 20:47:47 method=POST path=/api/v1/users status=409 request_id=21b9869d-3ada-404b-9d48-bb45a38e4b7f duration_ms=146
|
||||
api_test.go:263: created=1 conflict=7
|
||||
api_test.go:267: ✓ UNIQUE username выдержал гонку
|
||||
--- PASS: TestDuplicateUsernameRace (0.15s)
|
||||
=== RUN TestChatCreateRollsBack
|
||||
2026/10/14 22:42:43 method=POST path=/api/v1/users status=201 request_id=31a99df2-1cbb-4f6d-a0da-93874734b125 duration_ms=46
|
||||
api_test.go:216: создан roll_user_5dc7e0b5 id=b3e79e6a-0372-4ddb-b42b-88faf144cffa
|
||||
2026/10/14 22:42:43 method=POST path=/api/v1/auth/sessions status=201 request_id=7df88d52-ca91-4117-b0d8-e67873c30a8e duration_ms=47
|
||||
api_test.go:217: сессия выпущена, длина токена=64 (значение не печатаем)
|
||||
api_test.go:220: → создание чата с несуществующим участником должно откатиться, title=rollback-c249f42e-7e4b-45e5-899f-fca7fb2c8748
|
||||
2026/10/14 22:42:43 method=POST path=/api/v1/chats status=400 request_id=f5e498dd-c82e-449a-beba-a95a8d7bd4f2 duration_ms=7
|
||||
api_test.go:223: status=400 body={"error":{"code":"invalid_request","message":"unknown member","request_id":"f5e498dd-c82e-449a-beba-a95a8d7bd4f2"}}
|
||||
api_test.go:231: строк chats с этим title после ошибки: 0
|
||||
api_test.go:235: ✓ транзакция создания чата откатилась
|
||||
--- PASS: TestChatCreateRollsBack (0.11s)
|
||||
2026/10/29 20:47:47 method=POST path=/api/v1/users status=201 request_id=765ef8b2-1ab9-45a9-b1ca-c0a57ce2a0f2 duration_ms=46
|
||||
api_test.go:273: создан roll_user_bc438ea7 id=2b1e6b30-af1f-43e3-9d1c-f5469a3cc9b2
|
||||
2026/10/29 20:47:47 method=POST path=/api/v1/auth/sessions status=201 request_id=bce48af8-35b8-445e-8199-a67baac89a9a duration_ms=50
|
||||
api_test.go:274: сессия выпущена, длина токена=64 (значение не печатаем)
|
||||
api_test.go:277: → создание чата с несуществующим участником должно откатиться, title=rollback-019abedb-6bd0-4e42-a80e-2926f17210d5
|
||||
2026/10/29 20:47:47 method=POST path=/api/v1/chats status=400 request_id=5039fdb4-e9b2-4efc-8df9-87f23b0963bc duration_ms=7
|
||||
api_test.go:280: status=400 body={"error":{"code":"invalid_request","message":"unknown member","request_id":"5039fdb4-e9b2-4efc-8df9-87f23b0963bc"}}
|
||||
api_test.go:288: строк chats с этим title после ошибки: 0
|
||||
api_test.go:292: ✓ транзакция создания чата откатилась
|
||||
--- PASS: TestChatCreateRollsBack (0.12s)
|
||||
=== RUN TestPaginationPages
|
||||
api_test.go:241: → три сообщения, две страницы limit=2, затем последняя
|
||||
2026/10/14 22:42:43 method=POST path=/api/v1/users status=201 request_id=5c1c6082-a8cd-4b01-99b2-160271bbce01 duration_ms=49
|
||||
api_test.go:242: создан page_user_89c36669 id=d89903f6-8866-43f7-b83d-c119cf945dc9
|
||||
2026/10/14 22:42:43 method=POST path=/api/v1/auth/sessions status=201 request_id=4ff6d887-e45d-47f8-8781-b2a8bf302dd6 duration_ms=46
|
||||
api_test.go:243: сессия выпущена, длина токена=64 (значение не печатаем)
|
||||
2026/10/14 22:42:43 method=POST path=/api/v1/chats status=201 request_id=e2552d9a-60ee-4b51-a7a8-541195f8c154 duration_ms=5
|
||||
2026/10/14 22:42:43 method=POST path=/api/v1/chats/0049a8b1-72ff-4d15-935c-7630c261f0d3/messages status=201 request_id=3de7ef09-36db-4d9f-8f76-ed4e4895a661 duration_ms=5
|
||||
2026/10/14 22:42:43 method=POST path=/api/v1/chats/0049a8b1-72ff-4d15-935c-7630c261f0d3/messages status=201 request_id=6461472e-b6c9-4c79-a676-807dbfac8e64 duration_ms=1
|
||||
2026/10/14 22:42:43 method=POST path=/api/v1/chats/0049a8b1-72ff-4d15-935c-7630c261f0d3/messages status=201 request_id=57164ec9-1914-489a-809d-b8dd483fd833 duration_ms=1
|
||||
2026/10/14 22:42:43 method=GET path=/api/v1/chats/0049a8b1-72ff-4d15-935c-7630c261f0d3/messages status=200 request_id=48fea270-e7bf-4f0c-b123-bce8eec0b836 duration_ms=2
|
||||
api_test.go:253: status=200 body={"items":[{"chat_id":"0049a8b1-72ff-4d15-935c-7630c261f0d3","created_at":"2026-10-14T19:42:43.639Z","id":"ba4c7ac6-44f6-49da-9e93-dd6fc85c8bcb","sender_id":"d89903f6-8866-43f7-b83d-c119cf945dc9","text":"раз"},{"chat_id":"0049a8b1-72ff-4d15-935c-7630c261f0d3","created_at":"2026-10-14T19:42:43.643Z","id":"43302df0-2a23-4e84-929b-559d2d47ada1","sender_id":"d89903f6-8866-43f7-b83d-c119cf945dc9","te...
|
||||
2026/10/14 22:42:43 method=GET path=/api/v1/chats/0049a8b1-72ff-4d15-935c-7630c261f0d3/messages status=200 request_id=1277752d-bba6-4458-b304-9db0a01e6513 duration_ms=2
|
||||
api_test.go:261: status=200 body={"items":[{"chat_id":"0049a8b1-72ff-4d15-935c-7630c261f0d3","created_at":"2026-10-14T19:42:43.645Z","id":"187eb4f4-1ccf-4253-9737-3ec8ffbab89e","sender_id":"d89903f6-8866-43f7-b83d-c119cf945dc9","text":"три"}],"next_cursor":null}
|
||||
api_test.go:267: ✓ keyset обошёл историю без зависания cursor
|
||||
api_test.go:298: → три сообщения, две страницы limit=2, затем последняя
|
||||
2026/10/29 20:47:47 method=POST path=/api/v1/users status=201 request_id=bc986f66-b448-41cc-a599-be2a56fd5510 duration_ms=47
|
||||
api_test.go:299: создан page_user_aa1c2cf1 id=4adc24af-6e35-4b20-af6c-fbe71b273d13
|
||||
2026/10/29 20:47:47 method=POST path=/api/v1/auth/sessions status=201 request_id=e1932c08-f360-41b0-ac44-1e5abc82a683 duration_ms=47
|
||||
api_test.go:300: сессия выпущена, длина токена=64 (значение не печатаем)
|
||||
2026/10/29 20:47:47 method=POST path=/api/v1/chats status=201 request_id=b094e9bb-f051-4e9b-8870-7cca44a0f21b duration_ms=5
|
||||
2026/10/29 20:47:47 method=POST path=/api/v1/chats/3174a6a6-0a5a-4501-bd50-b82407e06d09/messages status=201 request_id=a99decf3-6451-44f1-848e-f1948af7bc9c duration_ms=3
|
||||
2026/10/29 20:47:47 method=POST path=/api/v1/chats/3174a6a6-0a5a-4501-bd50-b82407e06d09/messages status=201 request_id=ea05e96b-b706-49ad-9dff-3ffd08a369e5 duration_ms=1
|
||||
2026/10/29 20:47:47 method=POST path=/api/v1/chats/3174a6a6-0a5a-4501-bd50-b82407e06d09/messages status=201 request_id=5eae83cb-cdb5-4f2d-b538-53f0425361dc duration_ms=1
|
||||
2026/10/29 20:47:47 method=GET path=/api/v1/chats/3174a6a6-0a5a-4501-bd50-b82407e06d09/messages status=200 request_id=d4ebe393-78d5-48c4-8105-5264eb782f21 duration_ms=6
|
||||
api_test.go:310: status=200 body={"items":[{"chat_id":"3174a6a6-0a5a-4501-bd50-b82407e06d09","created_at":"2026-10-29T17:47:47.713Z","id":"54af40c1-7adb-4b9a-9b17-48ae8fcb90f5","sender_id":"4adc24af-6e35-4b20-af6c-fbe71b273d13","text":"раз"},{"chat_id":"3174a6a6-0a5a-4501-bd50-b82407e06d09","created_at":"2026-10-29T17:47:47.716Z","id":"5297094d-cfbc-494a-9cf6-414dddb12799","sender_id":"4adc24af-6e35-4b20-af6c-fbe71b273d13","te...
|
||||
2026/10/29 20:47:47 method=GET path=/api/v1/chats/3174a6a6-0a5a-4501-bd50-b82407e06d09/messages status=200 request_id=215b59b2-e18a-4084-be77-30b905a0acee duration_ms=2
|
||||
api_test.go:318: status=200 body={"items":[{"chat_id":"3174a6a6-0a5a-4501-bd50-b82407e06d09","created_at":"2026-10-29T17:47:47.718Z","id":"fee8dea4-7ad3-45fb-8e1a-0b662f10bd1a","sender_id":"4adc24af-6e35-4b20-af6c-fbe71b273d13","text":"три"}],"next_cursor":null}
|
||||
api_test.go:324: ✓ keyset обошёл историю без зависания cursor
|
||||
--- PASS: TestPaginationPages (0.12s)
|
||||
=== RUN TestRedisDownIsNotAnonymous
|
||||
api_test.go:271: → закрытый клиент Redis: вход и Bearer дают 503, а не 200 от анонима
|
||||
2026/10/14 22:42:43 method=POST path=/api/v1/users status=201 request_id=6d30a90b-f1f4-4952-b7f9-356316ed7bf0 duration_ms=46
|
||||
api_test.go:283: создан redis_down_64e13e26 id=2263b741-9519-489e-8d91-fe23cd9ff347
|
||||
2026/10/14 22:42:43 method=POST path=/api/v1/auth/sessions status=503 request_id=5dd380b7-9f8a-4bb9-b199-56373bedd5a6 duration_ms=44
|
||||
api_test.go:288: status=503 body={"error":{"code":"unavailable","message":"dependency unavailable","request_id":"5dd380b7-9f8a-4bb9-b199-56373bedd5a6"}}
|
||||
2026/10/14 22:42:43 method=GET path=/api/v1/users/me status=503 request_id=fc700303-3f23-499c-bf31-41330924d33b duration_ms=0
|
||||
api_test.go:295: status=503 body={"error":{"code":"unavailable","message":"dependency unavailable","request_id":"fc700303-3f23-499c-bf31-41330924d33b"}}
|
||||
api_test.go:299: ✓ сбой Redis не стал анонимным доступом
|
||||
--- PASS: TestRedisDownIsNotAnonymous (0.10s)
|
||||
api_test.go:328: → закрытый клиент Redis: вход и Bearer дают 503, а не 200 от анонима
|
||||
2026/10/29 20:47:47 method=POST path=/api/v1/users status=201 request_id=25fa4e88-d9fe-4446-9937-aa6ef93cd7e7 duration_ms=45
|
||||
api_test.go:340: создан redis_down_5857ff01 id=52eafe7c-1d01-41de-8acf-3dee2acfdcb7
|
||||
2026/10/29 20:47:47 method=POST path=/api/v1/auth/sessions status=503 request_id=77c2c160-6537-4f6a-b7ef-232c9df92d73 duration_ms=42
|
||||
api_test.go:344: status=503 body={"error":{"code":"unavailable","message":"dependency unavailable","request_id":"77c2c160-6537-4f6a-b7ef-232c9df92d73"}}
|
||||
2026/10/29 20:47:47 method=GET path=/api/v1/users/me status=503 request_id=ab53f69d-ae81-4e4e-9b8c-2a04897cb799 duration_ms=0
|
||||
api_test.go:351: status=503 body={"error":{"code":"unavailable","message":"dependency unavailable","request_id":"ab53f69d-ae81-4e4e-9b8c-2a04897cb799"}}
|
||||
api_test.go:355: ✓ сбой Redis не стал анонимным доступом
|
||||
--- PASS: TestRedisDownIsNotAnonymous (0.09s)
|
||||
=== RUN TestPostgresDownIsNotAnonymous
|
||||
api_test.go:359: → закрытый пул PostgreSQL: ready/me/login дают 503, без тела пользователя
|
||||
2026/10/29 20:47:47 method=POST path=/api/v1/users status=201 request_id=304dd490-79b5-48b3-afc7-170d561b0746 duration_ms=43
|
||||
api_test.go:362: создан pg_down_f780c9f0 id=5efd8a8b-2e35-495c-9a55-d45e2e6dd247
|
||||
2026/10/29 20:47:47 method=POST path=/api/v1/auth/sessions status=201 request_id=d84de0d4-0143-459b-9e3d-c4df8118ec8e duration_ms=55
|
||||
api_test.go:363: сессия выпущена, длина токена=64 (значение не печатаем)
|
||||
2026/10/29 20:47:48 method=GET path=/health/ready status=503 request_id=31940474-832b-429e-93ab-c3f2a7effc64 duration_ms=0
|
||||
api_test.go:384: status=503 body={"error":{"code":"unavailable","message":"dependency unavailable","request_id":"31940474-832b-429e-93ab-c3f2a7effc64"}}
|
||||
2026/10/29 20:47:48 method=GET path=/api/v1/users/me status=503 request_id=9fa69dbd-6f7c-4102-840e-996debe06aed duration_ms=0
|
||||
api_test.go:391: status=503 body={"error":{"code":"unavailable","message":"dependency unavailable","request_id":"9fa69dbd-6f7c-4102-840e-996debe06aed"}}
|
||||
2026/10/29 20:47:48 method=POST path=/api/v1/auth/sessions status=503 request_id=505c05d8-a2c2-4a5f-8d0d-624368ae068f duration_ms=0
|
||||
api_test.go:398: status=503 body={"error":{"code":"unavailable","message":"dependency unavailable","request_id":"505c05d8-a2c2-4a5f-8d0d-624368ae068f"}}
|
||||
api_test.go:402: ✓ сбой PostgreSQL не стал анонимным доступом
|
||||
--- PASS: TestPostgresDownIsNotAnonymous (0.18s)
|
||||
PASS
|
||||
ok mtusi2026lab2/student-tests 4.097s
|
||||
ok mtusi2026lab2/student-tests 4.827s
|
||||
|
||||
@@ -1,12 +1,12 @@
|
||||
{
|
||||
"explain": [
|
||||
{
|
||||
"Execution Time": 0.091,
|
||||
"Execution Time": 0.089,
|
||||
"Plan": {
|
||||
"Actual Loops": 1,
|
||||
"Actual Rows": 50,
|
||||
"Actual Startup Time": 0.061,
|
||||
"Actual Total Time": 0.075,
|
||||
"Actual Startup Time": 0.035,
|
||||
"Actual Total Time": 0.059,
|
||||
"Async Capable": false,
|
||||
"Local Dirtied Blocks": 0,
|
||||
"Local Hit Blocks": 0,
|
||||
@@ -14,18 +14,18 @@
|
||||
"Local Written Blocks": 0,
|
||||
"Node Type": "Limit",
|
||||
"Parallel Aware": false,
|
||||
"Plan Rows": 50,
|
||||
"Plan Rows": 1,
|
||||
"Plan Width": 24,
|
||||
"Plans": [
|
||||
{
|
||||
"Actual Loops": 1,
|
||||
"Actual Rows": 50,
|
||||
"Actual Startup Time": 0.06,
|
||||
"Actual Total Time": 0.068,
|
||||
"Actual Startup Time": 0.034,
|
||||
"Actual Total Time": 0.052,
|
||||
"Alias": "messages",
|
||||
"Async Capable": false,
|
||||
"Heap Fetches": 50,
|
||||
"Index Cond": "((chat_id = 'dd159fd8-b79e-4a15-a48c-4a84bd479430'::uuid) AND (ROW(created_at, id) \u003e ROW('2026-10-14 19:46:28.256+00'::timestamp with time zone, 'f051734d-6f81-440a-9253-0b417ccee2b1'::uuid)))",
|
||||
"Index Cond": "((chat_id = '8f7acbf7-3f3a-4512-b7d3-1018a9c57a24'::uuid) AND (ROW(created_at, id) \u003e ROW('2026-10-29 17:48:54.814+00'::timestamp with time zone, 'c7a07079-b045-42ef-b516-b5f4d9f08aec'::uuid)))",
|
||||
"Index Name": "messages_history_idx",
|
||||
"Local Dirtied Blocks": 0,
|
||||
"Local Hit Blocks": 0,
|
||||
@@ -34,29 +34,29 @@
|
||||
"Node Type": "Index Only Scan",
|
||||
"Parallel Aware": false,
|
||||
"Parent Relationship": "Outer",
|
||||
"Plan Rows": 167,
|
||||
"Plan Rows": 1,
|
||||
"Plan Width": 24,
|
||||
"Relation Name": "messages",
|
||||
"Rows Removed by Index Recheck": 0,
|
||||
"Scan Direction": "Forward",
|
||||
"Shared Dirtied Blocks": 0,
|
||||
"Shared Hit Blocks": 1,
|
||||
"Shared Read Blocks": 3,
|
||||
"Shared Read Blocks": 4,
|
||||
"Shared Written Blocks": 0,
|
||||
"Startup Cost": 0.42,
|
||||
"Temp Read Blocks": 0,
|
||||
"Temp Written Blocks": 0,
|
||||
"Total Cost": 635.76
|
||||
"Total Cost": 8.44
|
||||
}
|
||||
],
|
||||
"Shared Dirtied Blocks": 0,
|
||||
"Shared Hit Blocks": 1,
|
||||
"Shared Read Blocks": 3,
|
||||
"Shared Read Blocks": 4,
|
||||
"Shared Written Blocks": 0,
|
||||
"Startup Cost": 0.42,
|
||||
"Temp Read Blocks": 0,
|
||||
"Temp Written Blocks": 0,
|
||||
"Total Cost": 190.64
|
||||
"Total Cost": 8.44
|
||||
},
|
||||
"Planning": {
|
||||
"Local Dirtied Blocks": 0,
|
||||
@@ -70,7 +70,7 @@
|
||||
"Temp Read Blocks": 0,
|
||||
"Temp Written Blocks": 0
|
||||
},
|
||||
"Planning Time": 0.17,
|
||||
"Planning Time": 0.282,
|
||||
"Triggers": []
|
||||
}
|
||||
]
|
||||
|
||||
@@ -1,12 +1,12 @@
|
||||
{
|
||||
"explain": [
|
||||
{
|
||||
"Execution Time": 16.435,
|
||||
"Execution Time": 16.287,
|
||||
"Plan": {
|
||||
"Actual Loops": 1,
|
||||
"Actual Rows": 50,
|
||||
"Actual Startup Time": 16.393,
|
||||
"Actual Total Time": 16.403,
|
||||
"Actual Startup Time": 16.235,
|
||||
"Actual Total Time": 16.245,
|
||||
"Async Capable": false,
|
||||
"Local Dirtied Blocks": 0,
|
||||
"Local Hit Blocks": 0,
|
||||
@@ -14,14 +14,14 @@
|
||||
"Local Written Blocks": 0,
|
||||
"Node Type": "Limit",
|
||||
"Parallel Aware": false,
|
||||
"Plan Rows": 50,
|
||||
"Plan Rows": 1,
|
||||
"Plan Width": 24,
|
||||
"Plans": [
|
||||
{
|
||||
"Actual Loops": 1,
|
||||
"Actual Rows": 50,
|
||||
"Actual Startup Time": 16.392,
|
||||
"Actual Total Time": 16.396,
|
||||
"Actual Startup Time": 16.234,
|
||||
"Actual Total Time": 16.238,
|
||||
"Async Capable": false,
|
||||
"Local Dirtied Blocks": 0,
|
||||
"Local Hit Blocks": 0,
|
||||
@@ -30,18 +30,18 @@
|
||||
"Node Type": "Sort",
|
||||
"Parallel Aware": false,
|
||||
"Parent Relationship": "Outer",
|
||||
"Plan Rows": 167,
|
||||
"Plan Rows": 1,
|
||||
"Plan Width": 24,
|
||||
"Plans": [
|
||||
{
|
||||
"Actual Loops": 1,
|
||||
"Actual Rows": 44448,
|
||||
"Actual Startup Time": 4.156,
|
||||
"Actual Total Time": 10.771,
|
||||
"Actual Startup Time": 4.107,
|
||||
"Actual Total Time": 10.993,
|
||||
"Alias": "messages",
|
||||
"Async Capable": false,
|
||||
"Exact Heap Blocks": 847,
|
||||
"Filter": "(ROW(created_at, id) \u003e ROW('2026-10-14 19:46:28.256+00'::timestamp with time zone, 'f051734d-6f81-440a-9253-0b417ccee2b1'::uuid))",
|
||||
"Filter": "(ROW(created_at, id) \u003e ROW('2026-10-29 17:48:54.814+00'::timestamp with time zone, 'c7a07079-b045-42ef-b516-b5f4d9f08aec'::uuid))",
|
||||
"Local Dirtied Blocks": 0,
|
||||
"Local Hit Blocks": 0,
|
||||
"Local Read Blocks": 0,
|
||||
@@ -50,16 +50,16 @@
|
||||
"Node Type": "Bitmap Heap Scan",
|
||||
"Parallel Aware": false,
|
||||
"Parent Relationship": "Outer",
|
||||
"Plan Rows": 167,
|
||||
"Plan Rows": 1,
|
||||
"Plan Width": 24,
|
||||
"Plans": [
|
||||
{
|
||||
"Actual Loops": 1,
|
||||
"Actual Rows": 74449,
|
||||
"Actual Startup Time": 1.682,
|
||||
"Actual Total Time": 1.683,
|
||||
"Actual Startup Time": 1.697,
|
||||
"Actual Total Time": 1.698,
|
||||
"Async Capable": false,
|
||||
"Index Cond": "(chat_id = 'dd159fd8-b79e-4a15-a48c-4a84bd479430'::uuid)",
|
||||
"Index Cond": "(chat_id = '8f7acbf7-3f3a-4512-b7d3-1018a9c57a24'::uuid)",
|
||||
"Index Name": "messages_chat_only_idx",
|
||||
"Local Dirtied Blocks": 0,
|
||||
"Local Hit Blocks": 0,
|
||||
@@ -68,7 +68,7 @@
|
||||
"Node Type": "Bitmap Index Scan",
|
||||
"Parallel Aware": false,
|
||||
"Parent Relationship": "Outer",
|
||||
"Plan Rows": 500,
|
||||
"Plan Rows": 3,
|
||||
"Plan Width": 0,
|
||||
"Shared Dirtied Blocks": 0,
|
||||
"Shared Hit Blocks": 0,
|
||||
@@ -77,10 +77,10 @@
|
||||
"Startup Cost": 0,
|
||||
"Temp Read Blocks": 0,
|
||||
"Temp Written Blocks": 0,
|
||||
"Total Cost": 8.04
|
||||
"Total Cost": 4.32
|
||||
}
|
||||
],
|
||||
"Recheck Cond": "(chat_id = 'dd159fd8-b79e-4a15-a48c-4a84bd479430'::uuid)",
|
||||
"Recheck Cond": "(chat_id = '8f7acbf7-3f3a-4512-b7d3-1018a9c57a24'::uuid)",
|
||||
"Relation Name": "messages",
|
||||
"Rows Removed by Filter": 30001,
|
||||
"Rows Removed by Index Recheck": 0,
|
||||
@@ -88,10 +88,10 @@
|
||||
"Shared Hit Blocks": 847,
|
||||
"Shared Read Blocks": 66,
|
||||
"Shared Written Blocks": 0,
|
||||
"Startup Cost": 8.08,
|
||||
"Startup Cost": 4.32,
|
||||
"Temp Read Blocks": 0,
|
||||
"Temp Written Blocks": 0,
|
||||
"Total Cost": 918.22
|
||||
"Total Cost": 15.91
|
||||
}
|
||||
],
|
||||
"Shared Dirtied Blocks": 0,
|
||||
@@ -105,20 +105,20 @@
|
||||
"Sort Method": "top-N heapsort",
|
||||
"Sort Space Type": "Memory",
|
||||
"Sort Space Used": 28,
|
||||
"Startup Cost": 923.77,
|
||||
"Startup Cost": 15.92,
|
||||
"Temp Read Blocks": 0,
|
||||
"Temp Written Blocks": 0,
|
||||
"Total Cost": 924.19
|
||||
"Total Cost": 15.92
|
||||
}
|
||||
],
|
||||
"Shared Dirtied Blocks": 0,
|
||||
"Shared Hit Blocks": 847,
|
||||
"Shared Read Blocks": 66,
|
||||
"Shared Written Blocks": 0,
|
||||
"Startup Cost": 923.77,
|
||||
"Startup Cost": 15.92,
|
||||
"Temp Read Blocks": 0,
|
||||
"Temp Written Blocks": 0,
|
||||
"Total Cost": 923.89
|
||||
"Total Cost": 15.92
|
||||
},
|
||||
"Planning": {
|
||||
"Local Dirtied Blocks": 0,
|
||||
@@ -132,7 +132,7 @@
|
||||
"Temp Read Blocks": 0,
|
||||
"Temp Written Blocks": 0
|
||||
},
|
||||
"Planning Time": 0.131,
|
||||
"Planning Time": 0.165,
|
||||
"Triggers": []
|
||||
}
|
||||
]
|
||||
|
||||
@@ -3,11 +3,11 @@
|
||||
"counts_match": true,
|
||||
"first_id_match": true,
|
||||
"restore_chats": 6,
|
||||
"restore_first_id": "4f8212c8-fea5-4870-989c-b5edf0dfdcf5",
|
||||
"restore_first_id": "27220db3-c3ed-46b6-96c2-0cecaa48e77c",
|
||||
"restore_messages": 100000,
|
||||
"restore_sha256": "a6cec9d9dbd5898032730f587fdd6fad981f64360584ccfe6da60384b87e28c9",
|
||||
"restore_sha256": "f130fa3a20fac69679ab0b6aabcd54fb5ca36a403b8429d5953762eae424a57c",
|
||||
"source_chats": 6,
|
||||
"source_first_id": "4f8212c8-fea5-4870-989c-b5edf0dfdcf5",
|
||||
"source_first_id": "27220db3-c3ed-46b6-96c2-0cecaa48e77c",
|
||||
"source_messages": 100000,
|
||||
"source_sha256": "a6cec9d9dbd5898032730f587fdd6fad981f64360584ccfe6da60384b87e28c9"
|
||||
"source_sha256": "f130fa3a20fac69679ab0b6aabcd54fb5ca36a403b8429d5953762eae424a57c"
|
||||
}
|
||||
|
||||
@@ -0,0 +1,5 @@
|
||||
{
|
||||
"pg_restore_seconds": 1.256,
|
||||
"boundary": "wall clock around `docker compose exec pg_restore` only; empty DB already created; before checksum verify",
|
||||
"tool": "pg_restore -Fc --no-owner --exit-on-error"
|
||||
}
|
||||
@@ -1,5 +1,6 @@
|
||||
prepared messages=100000 chats=6
|
||||
weak: node=Limit execution_ms=16.435 shared_hit_blocks=847 sort=true
|
||||
strong: node=Limit execution_ms=0.091 shared_hit_blocks=1 sort=false
|
||||
write: only_chat_id_index_ms=30 chat_id_plus_history_ms=31 rows=5000
|
||||
weak: node=Limit execution_ms=16.287 shared_hit_blocks=847 sort=true
|
||||
strong: node=Limit execution_ms=0.089 shared_hit_blocks=1 sort=false
|
||||
write: only_chat_id_index_ms=38 chat_id_plus_history_ms=49 rows=5000
|
||||
pg_restore_seconds=1.256
|
||||
restore match counts=true checksum=true messages=100000
|
||||
|
||||
@@ -2,12 +2,12 @@
|
||||
"cursor_offset": 30000,
|
||||
"largest_chat_messages": 74449,
|
||||
"strong_index": "messages_history_idx (chat_id, created_at, id)",
|
||||
"strong_plan": "node=Limit execution_ms=0.091 shared_hit_blocks=1 sort=false",
|
||||
"strong_plan": "node=Limit execution_ms=0.089 shared_hit_blocks=1 sort=false",
|
||||
"weak_index": "messages_chat_only_idx (chat_id)",
|
||||
"weak_plan": "node=Limit execution_ms=16.435 shared_hit_blocks=847 sort=true",
|
||||
"weak_plan": "node=Limit execution_ms=16.287 shared_hit_blocks=847 sort=true",
|
||||
"write_cost": {
|
||||
"chat_id_plus_history_ms": 31,
|
||||
"only_chat_id_index_ms": 30,
|
||||
"chat_id_plus_history_ms": 49,
|
||||
"only_chat_id_index_ms": 38,
|
||||
"rows": 5000
|
||||
}
|
||||
}
|
||||
|
||||
+25
-5
@@ -11,11 +11,13 @@
|
||||
package api
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/base64"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"log"
|
||||
"net/http"
|
||||
"os"
|
||||
@@ -126,6 +128,16 @@ func (s *Server) handleCreateUser(w http.ResponseWriter, r *http.Request) {
|
||||
}
|
||||
|
||||
func (s *Server) handleCreateSession(w http.ResponseWriter, r *http.Request) {
|
||||
// Контракт: только Basic, без JSON body. Любые байты в теле — 400, не тихий игнор.
|
||||
rawBody, err := io.ReadAll(io.LimitReader(r.Body, 4096))
|
||||
if err != nil {
|
||||
writeError(w, r, http.StatusBadRequest, "invalid_request", "invalid body")
|
||||
return
|
||||
}
|
||||
if len(bytes.TrimSpace(rawBody)) != 0 {
|
||||
writeError(w, r, http.StatusBadRequest, "invalid_request", "session create must not have a body")
|
||||
return
|
||||
}
|
||||
username, password, ok := parseBasic(r.Header.Get("Authorization"))
|
||||
if !ok || !validUsername(username) {
|
||||
writeAuthError(w, r, challengeBasic)
|
||||
@@ -287,12 +299,13 @@ func (s *Server) handleCreateMessage(w http.ResponseWriter, r *http.Request) {
|
||||
writeDecodeErr(w, r, err)
|
||||
return
|
||||
}
|
||||
text := strings.TrimSpace(body.Text)
|
||||
if text == "" || utf8.RuneCountInString(text) > 4000 {
|
||||
// Непустота — по TrimSpace; длина и сохранение — по исходному тексту.
|
||||
// Иначе пробелы по краям пропадают, а строка «пробел + 4000 букв» проходит как 4000.
|
||||
if strings.TrimSpace(body.Text) == "" || utf8.RuneCountInString(body.Text) > 4000 {
|
||||
writeError(w, r, http.StatusBadRequest, "invalid_request", "invalid text")
|
||||
return
|
||||
}
|
||||
msg, err := s.Store.CreateMessage(r.Context(), chatID, userFrom(r), text)
|
||||
msg, err := s.Store.CreateMessage(r.Context(), chatID, userFrom(r), body.Text)
|
||||
if errors.Is(err, store.ErrNotFound) {
|
||||
writeError(w, r, http.StatusNotFound, "not_found", "object not found")
|
||||
return
|
||||
@@ -472,12 +485,19 @@ func decodeStrict(r *http.Request, dst any) error {
|
||||
if ct != "" && !strings.HasPrefix(strings.ToLower(strings.TrimSpace(ct)), "application/json") {
|
||||
return errUnsupported
|
||||
}
|
||||
dec := json.NewDecoder(r.Body)
|
||||
// Читаем тело целиком: Decoder.More() не ловит хвост вида {"text":"x"}} —
|
||||
// после одного объекта More()=false, а лишняя скобка всё равно остаётся.
|
||||
raw, err := io.ReadAll(io.LimitReader(r.Body, 1<<20))
|
||||
if err != nil {
|
||||
return errMalformed
|
||||
}
|
||||
dec := json.NewDecoder(bytes.NewReader(raw))
|
||||
dec.DisallowUnknownFields()
|
||||
if err := dec.Decode(dst); err != nil {
|
||||
return errMalformed
|
||||
}
|
||||
if dec.More() {
|
||||
rest := bytes.TrimSpace(raw[dec.InputOffset():])
|
||||
if len(rest) != 0 {
|
||||
return errMalformed
|
||||
}
|
||||
return nil
|
||||
|
||||
@@ -470,6 +470,7 @@ func isConn(err error) bool {
|
||||
if stringsContains(msg, "connection refused") ||
|
||||
stringsContains(msg, "failed to connect") ||
|
||||
stringsContains(msg, "conn closed") ||
|
||||
stringsContains(msg, "closed pool") ||
|
||||
stringsContains(msg, "broken pipe") ||
|
||||
stringsContains(msg, "connection reset") ||
|
||||
stringsContains(msg, "SQLSTATE 57P01") ||
|
||||
|
||||
+74
-22
@@ -1,42 +1,94 @@
|
||||
#!/bin/sh
|
||||
# Показывает, что остановленный Redis или PostgreSQL даёт 503, а не успешный анонимный ответ.
|
||||
# Контейнеры в конце снова запущены. Токены в вывод не попадают.
|
||||
# Автоматическая проверка отказа Redis и PostgreSQL.
|
||||
# Падает с ненулевым кодом, если ready/защищённый запрос ведут себя неверно.
|
||||
# Контейнеры в конце снова подняты. Токены в stdout не печатаются.
|
||||
set -eu
|
||||
ROOT=$(CDPATH= cd -- "$(dirname "$0")/.." && pwd)
|
||||
cd "$ROOT"
|
||||
BASE=${BASE_URL:-http://127.0.0.1:8080}
|
||||
|
||||
ready() {
|
||||
curl -s -o /tmp/lab2-ready-body -w "%{http_code}" "$BASE/health/ready" || echo "curl_fail"
|
||||
curl -s -o /tmp/lab2-ready-body -w "%{http_code}" "$BASE/health/ready" || echo "000"
|
||||
}
|
||||
|
||||
echo "ready_before=$(ready)"
|
||||
# Защищённый GET без печати токена. Ожидаем конкретный HTTP-код.
|
||||
me_status() {
|
||||
token=$1
|
||||
curl -s -o /tmp/lab2-me-body -w "%{http_code}" \
|
||||
-H "Authorization: Bearer ${token}" \
|
||||
"$BASE/api/v1/users/me" || echo "000"
|
||||
}
|
||||
|
||||
assert_eq() {
|
||||
name=$1
|
||||
got=$2
|
||||
want=$3
|
||||
echo "${name}=${got} (want ${want})"
|
||||
if [ "$got" != "$want" ]; then
|
||||
echo "FAIL: ${name}: got ${got}, want ${want}" >&2
|
||||
exit 1
|
||||
fi
|
||||
}
|
||||
|
||||
wait_ready() {
|
||||
i=0
|
||||
while [ "$i" -lt 30 ]; do
|
||||
code=$(ready)
|
||||
if [ "$code" = "200" ]; then
|
||||
echo "$code"
|
||||
return 0
|
||||
fi
|
||||
i=$((i + 1))
|
||||
sleep 1
|
||||
done
|
||||
echo "$code"
|
||||
return 1
|
||||
}
|
||||
|
||||
# Синтетический пользователь только для проверки 503 на Bearer.
|
||||
suffix=$(date +%s)
|
||||
user_body=$(printf '{"username":"dep_%s","display_name":"Deps","password":"correct-horse-1"}' "$suffix")
|
||||
reg=$(curl -s -o /tmp/lab2-reg.json -w "%{http_code}" -H 'Content-Type: application/json' \
|
||||
-d "$user_body" "$BASE/api/v1/users")
|
||||
assert_eq "register" "$reg" "201"
|
||||
auth_hdr=$(printf 'Authorization: Basic %s' "$(printf 'dep_%s:correct-horse-1' "$suffix" | base64 | tr -d '\n')")
|
||||
# Пустое тело (-d '') обязательно: иначе curl сделает GET и получит 405.
|
||||
sess=$(curl -s -o /tmp/lab2-sess.json -w "%{http_code}" -X POST -d '' -H "$auth_hdr" \
|
||||
"$BASE/api/v1/auth/sessions")
|
||||
assert_eq "login" "$sess" "201"
|
||||
token=$(python3 -c 'import json; print(json.load(open("/tmp/lab2-sess.json"))["token"])')
|
||||
|
||||
assert_eq "ready_before" "$(ready)" "200"
|
||||
assert_eq "me_before" "$(me_status "$token")" "200"
|
||||
|
||||
echo "stop redis"
|
||||
docker compose --env-file .env stop redis
|
||||
sleep 1
|
||||
echo "ready_redis_down=$(ready)"
|
||||
assert_eq "ready_redis_down" "$(ready)" "503"
|
||||
assert_eq "me_redis_down" "$(me_status "$token")" "503"
|
||||
# Анонимный ответ недопустим: 200 с телом пользователя = провал.
|
||||
if grep -q '"username"' /tmp/lab2-me-body 2>/dev/null; then
|
||||
echo "FAIL: redis down returned user payload" >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
echo "start redis"
|
||||
docker compose --env-file .env start redis
|
||||
for _ in 1 2 3 4 5 6 7 8 9 10; do
|
||||
code=$(ready)
|
||||
if [ "$code" = "200" ]; then
|
||||
break
|
||||
fi
|
||||
sleep 1
|
||||
done
|
||||
echo "ready_redis_back=$code"
|
||||
assert_eq "ready_redis_back" "$(wait_ready)" "200"
|
||||
assert_eq "me_redis_back" "$(me_status "$token")" "200"
|
||||
|
||||
echo "stop postgres"
|
||||
docker compose --env-file .env stop postgres
|
||||
sleep 1
|
||||
echo "ready_postgres_down=$(ready)"
|
||||
assert_eq "ready_postgres_down" "$(ready)" "503"
|
||||
assert_eq "me_postgres_down" "$(me_status "$token")" "503"
|
||||
if grep -q '"username"' /tmp/lab2-me-body 2>/dev/null; then
|
||||
echo "FAIL: postgres down returned user payload" >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
echo "start postgres"
|
||||
docker compose --env-file .env start postgres
|
||||
for _ in 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15; do
|
||||
code=$(ready)
|
||||
if [ "$code" = "200" ]; then
|
||||
break
|
||||
fi
|
||||
sleep 1
|
||||
done
|
||||
echo "ready_postgres_back=$code"
|
||||
assert_eq "ready_postgres_back" "$(wait_ready)" "200"
|
||||
assert_eq "me_postgres_back" "$(me_status "$token")" "200"
|
||||
echo "PASS: dependency outages return 503 and recover"
|
||||
|
||||
+3
-14
@@ -1,19 +1,8 @@
|
||||
#!/bin/sh
|
||||
# Перезапуск API и обоих хранилищ без удаления volumes и без повторного seed.
|
||||
# Тест сохранности сам дождётся /health/ready. Скрипт только инициирует restart.
|
||||
# Важно: нужен именно restart сервиса api, а не up -d: у уже работающего контейнера
|
||||
# up -d --no-build не меняет PID/StartedAt, и persistence-проверка это замечает.
|
||||
set -eu
|
||||
ROOT=$(CDPATH= cd -- "$(dirname "$0")/.." && pwd)
|
||||
cd "$ROOT"
|
||||
# Сначала хранилища, затем API. API ещё и сам ждёт порт БД до 45 секунд,
|
||||
# если restart поднимет его раньше, чем Postgres примет соединения.
|
||||
docker compose --env-file .env restart postgres redis
|
||||
i=0
|
||||
while [ "$i" -lt 40 ]; do
|
||||
if docker compose --env-file .env exec -T postgres pg_isready -U "${POSTGRES_USER:-messenger}" -d "${POSTGRES_DB:-messenger}" >/dev/null 2>&1 \
|
||||
&& docker compose --env-file .env exec -T redis redis-cli ping >/dev/null 2>&1; then
|
||||
break
|
||||
fi
|
||||
i=$((i + 1))
|
||||
sleep 1
|
||||
done
|
||||
docker compose --env-file .env up -d --no-deps --no-build api
|
||||
docker compose --env-file .env restart postgres redis api
|
||||
|
||||
+26
-1
@@ -14,6 +14,8 @@ USER=${POSTGRES_USER:-messenger}
|
||||
PASS=${POSTGRES_PASSWORD:-messenger}
|
||||
export PATH="/opt/homebrew/bin:/usr/bin:/bin:$PATH"
|
||||
|
||||
mkdir -p evidence/track2
|
||||
|
||||
docker compose --env-file .env exec -T postgres psql -U "$USER" -d postgres -v ON_ERROR_STOP=1 -c "SELECT 1" >/dev/null
|
||||
docker compose --env-file .env exec -T postgres createdb -U "$USER" track2 2>/dev/null || true
|
||||
docker compose --env-file .env exec -T postgres createdb -U "$USER" track2_restore 2>/dev/null || true
|
||||
@@ -29,6 +31,29 @@ docker compose --env-file .env exec -T postgres psql -U "$USER" -d postgres -v O
|
||||
-c "SELECT pg_terminate_backend(pid) FROM pg_stat_activity WHERE datname = 'track2_restore' AND pid <> pg_backend_pid();" \
|
||||
-c "DROP DATABASE IF EXISTS track2_restore" \
|
||||
-c "CREATE DATABASE track2_restore"
|
||||
docker compose --env-file .env exec -T postgres pg_restore -U "$USER" -d track2_restore --no-owner --exit-on-error /tmp/track2.dump
|
||||
|
||||
# Граница замера: только pg_restore в уже созданную пустую track2_restore.
|
||||
# Не включает prepare/explain/dump/verify и не включает DROP/CREATE DATABASE.
|
||||
python3 - <<'PY'
|
||||
import json, subprocess, time
|
||||
from pathlib import Path
|
||||
cmd = [
|
||||
"docker", "compose", "--env-file", ".env", "exec", "-T", "postgres",
|
||||
"pg_restore", "-U", "messenger", "-d", "track2_restore",
|
||||
"--no-owner", "--exit-on-error", "/tmp/track2.dump",
|
||||
]
|
||||
t0 = time.perf_counter()
|
||||
subprocess.check_call(cmd)
|
||||
seconds = round(time.perf_counter() - t0, 3)
|
||||
Path("evidence/track2/restore_timing.json").write_text(
|
||||
json.dumps({
|
||||
"pg_restore_seconds": seconds,
|
||||
"boundary": "wall clock around `docker compose exec pg_restore` only; empty DB already created; before checksum verify",
|
||||
"tool": "pg_restore -Fc --no-owner --exit-on-error",
|
||||
}, ensure_ascii=False, indent=2) + "\n"
|
||||
)
|
||||
print(f"pg_restore_seconds={seconds}")
|
||||
PY
|
||||
|
||||
go run ./cmd/track2 -mode verify -database-url "$SRC" -restore-url "$DST" -out evidence/track2
|
||||
echo "track2 ok"
|
||||
|
||||
+107
-4
@@ -70,7 +70,7 @@ func TestMain(m *testing.M) {
|
||||
func TestMalformedJSONAndValidation(t *testing.T) {
|
||||
srv := newAPI(t, time.Hour)
|
||||
defer srv.Close()
|
||||
logStep(t, "битый JSON, лишнее поле, пустой текст, чужой чат")
|
||||
logStep(t, "битый JSON, хвост после объекта, лишнее поле, пустой текст, чужой чат")
|
||||
|
||||
status, body := do(t, srv, http.MethodPost, "/api/v1/users", nil, "{")
|
||||
logResult(t, status, body)
|
||||
@@ -88,7 +88,18 @@ func TestMalformedJSONAndValidation(t *testing.T) {
|
||||
user := register(t, srv, "ok_user")
|
||||
token := login(t, srv, user.username, user.password)
|
||||
chat := createChat(t, srv, token, user.id, "Чат проверки")
|
||||
status, body = do(t, srv, http.MethodPost, "/api/v1/chats/"+chat+"/messages", map[string]string{"Authorization": "Bearer " + token}, `{"text":" "}`)
|
||||
auth := map[string]string{"Authorization": "Bearer " + token}
|
||||
|
||||
// Decoder.More() это не ловит: один объект декодируется, лишняя скобка остаётся.
|
||||
for _, raw := range []string{`{"text":"valid"}}`, `{"text":"valid"}]`} {
|
||||
status, body = do(t, srv, http.MethodPost, "/api/v1/chats/"+chat+"/messages", auth, raw)
|
||||
logResult(t, status, body)
|
||||
if status != http.StatusBadRequest {
|
||||
t.Fatalf("trailing garbage %q: status=%d body=%s", raw, status, body)
|
||||
}
|
||||
}
|
||||
|
||||
status, body = do(t, srv, http.MethodPost, "/api/v1/chats/"+chat+"/messages", auth, `{"text":" "}`)
|
||||
logResult(t, status, body)
|
||||
if status != http.StatusBadRequest {
|
||||
t.Fatalf("blank message: status=%d", status)
|
||||
@@ -101,7 +112,53 @@ func TestMalformedJSONAndValidation(t *testing.T) {
|
||||
if status != http.StatusNotFound {
|
||||
t.Fatalf("foreign chat: status=%d body=%s", status, body)
|
||||
}
|
||||
logOK(t, "валидация JSON, пустого текста и чужого чата")
|
||||
logOK(t, "валидация JSON, хвоста, пустого текста и чужого чата")
|
||||
}
|
||||
|
||||
func TestMessageTextPreservedAndLengthOnOriginal(t *testing.T) {
|
||||
srv := newAPI(t, time.Hour)
|
||||
defer srv.Close()
|
||||
logStep(t, "пробелы по краям сохраняются; длина считается по исходному тексту")
|
||||
user := register(t, srv, "text_user")
|
||||
token := login(t, srv, user.username, user.password)
|
||||
chat := createChat(t, srv, token, user.id, "Текст")
|
||||
auth := map[string]string{"Authorization": "Bearer " + token}
|
||||
|
||||
original := " строка\nс пробелами "
|
||||
status, body := do(t, srv, http.MethodPost, "/api/v1/chats/"+chat+"/messages", auth,
|
||||
fmt.Sprintf(`{"text":%q}`, original))
|
||||
logResult(t, status, body)
|
||||
if status != http.StatusCreated {
|
||||
t.Fatalf("preserve spaces: status=%d", status)
|
||||
}
|
||||
got := decode(t, body)
|
||||
if got["text"] != original {
|
||||
t.Fatalf("text mutated: got %q want %q", got["text"], original)
|
||||
}
|
||||
|
||||
tooLong := " " + strings.Repeat("a", 4000) // 4001 code points
|
||||
status, body = do(t, srv, http.MethodPost, "/api/v1/chats/"+chat+"/messages", auth,
|
||||
fmt.Sprintf(`{"text":%q}`, tooLong))
|
||||
logResult(t, status, body)
|
||||
if status != http.StatusBadRequest {
|
||||
t.Fatalf("length after trim bypass: status=%d body=%s", status, body)
|
||||
}
|
||||
logOK(t, "текст сохранён целиком, обход лимита через TrimSpace закрыт")
|
||||
}
|
||||
|
||||
func TestSessionRejectsJSONBody(t *testing.T) {
|
||||
srv := newAPI(t, time.Hour)
|
||||
defer srv.Close()
|
||||
logStep(t, "POST /auth/sessions с телом должен быть 400 даже при верном Basic")
|
||||
user := register(t, srv, "body_user")
|
||||
status, body := do(t, srv, http.MethodPost, "/api/v1/auth/sessions", map[string]string{
|
||||
"Authorization": "Basic " + basic(user.username, user.password),
|
||||
}, `{"extra":1}`)
|
||||
logResult(t, status, body)
|
||||
if status != http.StatusBadRequest {
|
||||
t.Fatalf("session with body: status=%d body=%s", status, body)
|
||||
}
|
||||
logOK(t, "вход без JSON body")
|
||||
}
|
||||
|
||||
func TestWrongPasswordLogoutAndIgnoredUserHeader(t *testing.T) {
|
||||
@@ -281,7 +338,6 @@ func TestRedisDownIsNotAnonymous(t *testing.T) {
|
||||
regSrv := newAPI(t, time.Hour)
|
||||
defer regSrv.Close()
|
||||
user := register(t, regSrv, "redis_down")
|
||||
// register() opened another server; login against the closed-redis server.
|
||||
status, body := do(t, srv, http.MethodPost, "/api/v1/auth/sessions", map[string]string{
|
||||
"Authorization": "Basic " + basic(user.username, user.password),
|
||||
}, "")
|
||||
@@ -299,6 +355,53 @@ func TestRedisDownIsNotAnonymous(t *testing.T) {
|
||||
logOK(t, "сбой Redis не стал анонимным доступом")
|
||||
}
|
||||
|
||||
func TestPostgresDownIsNotAnonymous(t *testing.T) {
|
||||
logStep(t, "закрытый пул PostgreSQL: ready/me/login дают 503, без тела пользователя")
|
||||
regSrv := newAPI(t, time.Hour)
|
||||
defer regSrv.Close()
|
||||
user := register(t, regSrv, "pg_down")
|
||||
token := login(t, regSrv, user.username, user.password)
|
||||
|
||||
hasher, err := auth.NewHasher()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
dsn := getenv("DATABASE_URL", "postgres://messenger:messenger@127.0.0.1:5432/messenger?sslmode=disable")
|
||||
broken, err := store.Open(context.Background(), dsn, hasher)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
broken.Close()
|
||||
sessions, err := session.Open(sharedRedisURL, time.Hour)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Cleanup(func() { _ = sessions.Close() })
|
||||
srv := httptest.NewServer(api.New(broken, sessions).Handler())
|
||||
defer srv.Close()
|
||||
|
||||
status, body := do(t, srv, http.MethodGet, "/health/ready", nil, "")
|
||||
logResult(t, status, body)
|
||||
if status != http.StatusServiceUnavailable {
|
||||
t.Fatalf("ready with dead postgres: %d", status)
|
||||
}
|
||||
status, body = do(t, srv, http.MethodGet, "/api/v1/users/me", map[string]string{
|
||||
"Authorization": "Bearer " + token,
|
||||
}, "")
|
||||
logResult(t, status, body)
|
||||
if status != http.StatusServiceUnavailable || strings.Contains(body, `"username"`) {
|
||||
t.Fatalf("me with dead postgres: status=%d body=%s", status, body)
|
||||
}
|
||||
status, body = do(t, srv, http.MethodPost, "/api/v1/auth/sessions", map[string]string{
|
||||
"Authorization": "Basic " + basic(user.username, user.password),
|
||||
}, "")
|
||||
logResult(t, status, body)
|
||||
if status != http.StatusServiceUnavailable {
|
||||
t.Fatalf("login with dead postgres: status=%d body=%s", status, body)
|
||||
}
|
||||
logOK(t, "сбой PostgreSQL не стал анонимным доступом")
|
||||
}
|
||||
|
||||
type account struct {
|
||||
id string
|
||||
username string
|
||||
|
||||
Reference in New Issue
Block a user