This commit is contained in:
papapevagemabody
2026-10-09 19:25:05 +03:00
parent 65003b6119
commit 6489bb731d
45 changed files with 2537 additions and 37 deletions
+2
View File
@@ -0,0 +1,2 @@
python scripts/check_contract.py
PASS: offline skeleton structure, local refs and Python syntax; application NOT tested.␍
+26
View File
@@ -0,0 +1,26 @@
docker compose --profile tools run --rm db-test
20 параллельных create_user: 1 создан, 19 получили Conflict (409)
чат с несуществующим участником: транзакция откатилась, строк chats/chat_members не осталось
INSERT сообщения от не-участника напрямую в БД: ForeignKeyViolation
schema_migrations: ['001_core', '002_sessions']; повторный migrate() ничего не применил
Container mtusi-lab2-valkey-1 Running
Container mtusi-lab2-postgres-1 Running
Container mtusi-lab2-postgres-1 Waiting
Container mtusi-lab2-valkey-1 Waiting
Container mtusi-lab2-valkey-1 Healthy
Container mtusi-lab2-postgres-1 Healthy
Container mtusi-lab2-db-test-run-93339611c921 Creating
Container mtusi-lab2-db-test-run-93339611c921 Created
test_concurrent_registration_has_one_winner (test_store.StoreIntegrationTest.test_concurrent_registration_has_one_winner) ... ok
test_create_chat_rolls_back_when_failing_midway (test_store.StoreIntegrationTest.test_create_chat_rolls_back_when_failing_midway) ... ok
test_database_rejects_message_from_non_member (test_store.StoreIntegrationTest.test_database_rejects_message_from_non_member) ... ok
test_migrations_rerun_is_noop (test_store.StoreIntegrationTest.test_migrations_rerun_is_noop) ... ok
----------------------------------------------------------------------
Ran 4 tests in 0.118s
OK
+22
View File
@@ -0,0 +1,22 @@
docker compose --profile ttl up -d --wait api-short-ttl
Container mtusi-lab2-valkey-1 Running
Container mtusi-lab2-postgres-1 Running
Container mtusi-lab2-api-short-ttl-1 Creating
Container mtusi-lab2-api-short-ttl-1 Created
Container mtusi-lab2-valkey-1 Waiting
Container mtusi-lab2-postgres-1 Waiting
Container mtusi-lab2-valkey-1 Healthy
Container mtusi-lab2-postgres-1 Healthy
Container mtusi-lab2-api-short-ttl-1 Starting
Container mtusi-lab2-api-short-ttl-1 Started
Container mtusi-lab2-valkey-1 Waiting
Container mtusi-lab2-api-short-ttl-1 Waiting
Container mtusi-lab2-postgres-1 Waiting
Container mtusi-lab2-valkey-1 Healthy
Container mtusi-lab2-postgres-1 Healthy
Container mtusi-lab2-api-short-ttl-1 Healthy
python student-tests/expiry.py
session issued by short-TTL API, expires in 1.99s␍
before expiry: GET /users/me -> 200 (short API twice, main API once)␍
after expiry: GET /users/me -> 401 on both instances␍
PASS: session expired after SESSION_TTL_SECONDS; cache did not extend it␍
+71
View File
@@ -0,0 +1,71 @@
docker compose exec -T postgres psql -X -q -U messenger -d messenger -v ON_ERROR_STOP=1 < infra/sql/explain_history.sql
=== Объём данных
messages_total | messages_in_big_chat
----------------+----------------------
21614 | 12000
=== Индекс истории (migrations/001_core.sql)
indexdef
-------------------------------------------------------------------------------------------------
CREATE INDEX messages_chat_history_idx ON public.messages USING btree (chat_id, created_at, id)
=== 1. Первая страница (limit=50, приложение просит 51 строку, чтобы понять, есть ли следующая)
QUERY PLAN
---------------------------------------------------------------------------------------------------------
Limit (actual time=0.013..0.026 rows=51 loops=1)
Buffers: shared hit=4
-> Index Scan using messages_chat_history_idx on messages (actual time=0.012..0.022 rows=51 loops=1)
Index Cond: (chat_id = 'a94bac8d-03ea-4bc6-a6f6-54c7fa77fe8f'::uuid)
Buffers: shared hit=4
Planning:
Buffers: shared hit=6
Planning Time: 0.175 ms
Execution Time: 0.041 ms
=== 2. Страница из середины истории по keyset-курсору (после 6000-го сообщения)
QUERY PLAN
------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
Limit (actual time=0.018..0.033 rows=51 loops=1)
Buffers: shared hit=4
-> Index Scan using messages_chat_history_idx on messages (actual time=0.016..0.028 rows=51 loops=1)
Index Cond: ((chat_id = 'a94bac8d-03ea-4bc6-a6f6-54c7fa77fe8f'::uuid) AND (ROW(created_at, id) > ROW('2026-01-01 01:40:00+00'::timestamp with time zone, '42ee0870-5605-4719-8545-f4a6a0c5fa07'::uuid)))
Buffers: shared hit=4
Planning Time: 0.169 ms
Execution Time: 0.078 ms
=== 3. Для сравнения: та же страница через OFFSET (так приложение НЕ делает)
QUERY PLAN
-----------------------------------------------------------------------------------------------------------
Limit (actual time=1.277..1.287 rows=51 loops=1)
Buffers: shared hit=161
-> Index Scan using messages_chat_history_idx on messages (actual time=0.075..1.066 rows=6051 loops=1)
Index Cond: (chat_id = 'a94bac8d-03ea-4bc6-a6f6-54c7fa77fe8f'::uuid)
Buffers: shared hit=161
Planning Time: 0.165 ms
Execution Time: 1.321 ms
=== 4. Для сравнения: запрос 2 без индекса (индекс удалён только внутри этой транзакции)
QUERY PLAN
--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
Limit (actual time=2.335..2.341 rows=51 loops=1)
Buffers: shared hit=291
-> Sort (actual time=2.334..2.337 rows=51 loops=1)
Sort Key: created_at, id
Sort Method: top-N heapsort Memory: 31kB
Buffers: shared hit=291
-> Seq Scan on messages (actual time=0.559..1.828 rows=6000 loops=1)
Filter: ((chat_id = 'a94bac8d-03ea-4bc6-a6f6-54c7fa77fe8f'::uuid) AND (ROW(created_at, id) > ROW('2026-01-01 01:40:00+00'::timestamp with time zone, '42ee0870-5605-4719-8545-f4a6a0c5fa07'::uuid)))
Rows Removed by Filter: 15614
Buffers: shared hit=291
Planning:
Buffers: shared hit=4
Planning Time: 0.158 ms
Execution Time: 2.370 ms
=== ROLLBACK: синтетические данные удалены, индекс на месте
+12
View File
@@ -0,0 +1,12 @@
python student-tests/dependency_failure.py postgres
stopping postgres (docker compose stop postgres)␍
/health/live -> 200: процесс жив␍
/health/ready -> 503 (1031 ms): без PostgreSQL обслуживать нельзя␍
бизнес-запросы с действующим токеном -> 503 unavailable (без SQL и stack trace в ответе)␍
без токена -> 401: аноним не становится доверенным␍
неизвестный токен -> 503: не подтверждается ни кэшем, ни базой␍
вход -> 503: сессию без базы не выдаём␍
регистрация -> 503␍
starting postgres again␍
after recovery: прежний токен работает, подтверждённые сообщения на месте␍
PASS: postgres outage handled without trusting anonymous requests␍
+12
View File
@@ -0,0 +1,12 @@
python student-tests/dependency_failure.py valkey
stopping valkey (docker compose stop valkey)␍
/health/ready -> 200 (0 ms): Valkey не критичен, API готов␍
existing token: GET /users/me -> 200 (1141 ms), сессия проверена по PostgreSQL (этот запрос и обнаружил сбой кэша)␍
POST message -> 201, история читается␍
register + login new user -> 201␍
logout -> 204, затем тот же токен -> 401 (отзыв записан в PostgreSQL)␍
10 x GET /users/me без кэша: max 16 ms (кэш не ждём на каждом запросе)␍
через 6 с, ещё 10 x GET /users/me: max 32 ms (повторные попытки — в фоне)␍
starting valkey again␍
after recovery: прежний токен работает, подтверждённые сообщения на месте␍
PASS: valkey outage handled without trusting anonymous requests␍
+15
View File
@@ -0,0 +1,15 @@
docker compose ps -a --format "table {{.Service}}\t{{.ID}}\t{{.Status}}"
SERVICE CONTAINER ID STATUS
api a172387a0b1b Up About a minute (healthy)
postgres ba5b3bed8209 Up About a minute (healthy)
valkey 5b7bf292ad60 Up About a minute (healthy)
python tests/resilience.py --mode persistence --action-script "scripts/restart.cmd" --base-url "http://127.0.0.1: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.␍
docker compose ps -a --format "table {{.Service}}\t{{.ID}}\t{{.Status}}"
SERVICE CONTAINER ID STATUS
api a172387a0b1b Up 1 second (health: starting)
postgres ba5b3bed8209 Up 7 seconds (healthy)
valkey 5b7bf292ad60 Up 7 seconds (healthy)
api-1 | 2026-10-09 16:00:09,560 INFO messenger.db: Миграции применены: 001_core, 002_sessions
api-1 | 2026-10-09 16:02:00,061 INFO messenger.db: Миграции: новых нет, схема актуальна
+6
View File
@@ -0,0 +1,6 @@
python student-tests/race.py
messages: sent 100 from 10 parallel clients in 1.06s␍
messages: read 100 in 4 pages, unique ids: 100␍
PASS: 100 concurrent messages stored without loss or duplicates␍
registration: 20 parallel requests for one username -> 201 x1, 409 x19␍
PASS: concurrent registration of the same username created exactly one user␍
+35
View File
@@ -0,0 +1,35 @@
docker --version
Docker version 29.4.2, build 055a478
docker compose version
Docker Compose version v5.1.3
docker image ls --filter reference=mtusi-messenger:lab2
mtusi-messenger:lab2 800cc8415a95 57.7MB
docker image ls --filter reference=postgres:17.10-bookworm
postgres:17.10-bookworm 9b18b7839705 162MB
docker image ls --filter reference=valkey/valkey:8.1.9
valkey/valkey:8.1.9 d5e642b89ee0 46MB
docker compose ps -a --format "table {{.Service}}\t{{.ID}}\t{{.Status}}"
SERVICE CONTAINER ID STATUS
api a172387a0b1b Up 2 minutes (healthy)
api-short-ttl c3eb7a556a20 Up About a minute (healthy)
postgres ba5b3bed8209 Up About a minute (healthy)
valkey 5b7bf292ad60 Up About a minute (healthy)
docker compose logs api | findstr Миграц
api-1 | 2026-10-09 16:00:09,560 INFO messenger.db: Миграции применены: 001_core, 002_sessions
api-1 | 2026-10-09 16:02:00,061 INFO messenger.db: Миграции: новых нет, схема актуальна
docker compose exec -T api id
uid=10001(app) gid=999(app) groups=999(app)
docker compose exec -T postgres psql -X -q -U messenger -d messenger -c "SELECT left(password_hash, 30) FROM users LIMIT 1"
left
--------------------------------
$argon2id$v=19$m=19456,t=2,p=1
(1 row)
git check-ignore -v .env secrets/database_url
fatal: not a git repository (or any of the parent directories): .git
exit_code: 128
rules in .gitignore:
.env
secrets/
volumes/
data/
+27
View File
@@ -0,0 +1,27 @@
python -m unittest discover -s student-tests -p "test_*.py" -v
test_auth_checked_before_access_and_body (test_api.MessengerApiTest.test_auth_checked_before_access_and_body) ... ok␍
test_bad_cursor_returns_400 (test_api.MessengerApiTest.test_bad_cursor_returns_400) ... ok␍
test_chat_list_pagination (test_api.MessengerApiTest.test_chat_list_pagination) ... ok␍
test_chat_membership_rules (test_api.MessengerApiTest.test_chat_membership_rules) ... ok␍
test_duplicate_username_returns_409 (test_api.MessengerApiTest.test_duplicate_username_returns_409) ... ok␍
test_empty_blank_and_too_long_messages_return_400 (test_api.MessengerApiTest.test_empty_blank_and_too_long_messages_return_400) ... ok␍
test_malformed_json_returns_400 (test_api.MessengerApiTest.test_malformed_json_returns_400) ... ok␍
test_outsider_gets_404_for_foreign_chat (test_api.MessengerApiTest.test_outsider_gets_404_for_foreign_chat) ... ok␍
test_pagination_walks_several_pages (test_api.MessengerApiTest.test_pagination_walks_several_pages) ... ok␍
test_unicode_roundtrip (test_api.MessengerApiTest.test_unicode_roundtrip) ... ok␍
test_wrong_types_and_extra_fields_return_400 (test_api.MessengerApiTest.test_wrong_types_and_extra_fields_return_400) ... ok␍
test_bearer_required_on_business_endpoints (test_auth.AuthTest.test_bearer_required_on_business_endpoints) ... ok␍
test_login_returns_opaque_token_with_expiry (test_auth.AuthTest.test_login_returns_opaque_token_with_expiry) ... ok␍
test_logout_revokes_only_current_session (test_auth.AuthTest.test_logout_revokes_only_current_session) ... ok␍
test_malformed_basic_returns_401 (test_auth.AuthTest.test_malformed_basic_returns_401) ... ok␍
test_password_length_rules (test_auth.AuthTest.test_password_length_rules) ... ok␍
test_password_with_colon_and_unicode (test_auth.AuthTest.test_password_with_colon_and_unicode) ... ok␍
test_relogin_after_logout (test_auth.AuthTest.test_relogin_after_logout) ... ok␍
test_user_never_contains_password (test_auth.AuthTest.test_user_never_contains_password) ... ok␍
test_wrong_password_and_unknown_user_look_the_same (test_auth.AuthTest.test_wrong_password_and_unknown_user_look_the_same) ... ok␍
test_x_user_id_does_not_change_identity (test_auth.AuthTest.test_x_user_id_does_not_change_identity) ... ok␍
␍
----------------------------------------------------------------------␍
Ran 21 tests in 2.586s␍
␍
OK␍
+2
View File
@@ -0,0 +1,2 @@
python tests/smoke.py --base-url "http://127.0.0.1:8080"
PASS: lab2 public API scenario; infrastructure and grading evidence remain separate.␍
+8
View File
@@ -0,0 +1,8 @@
docker compose exec -T valkey valkey-cli --user health --pass none --no-auth-warning dbsize
2
docker compose exec -T valkey valkey-cli --user health --pass none --no-auth-warning info stats | grep -E "keyspace_(hits|misses)"
keyspace_hits:14
keyspace_misses:2
docker compose exec -T valkey valkey-cli --user health --pass none --no-auth-warning get sess:anything
NOPERM User health has no permissions to run the 'get' command