forked from mtusi2026/mtusi2026lab2
ЛР2
This commit is contained in:
@@ -0,0 +1,2 @@
|
||||
python scripts/check_contract.py
|
||||
PASS: offline skeleton structure, local refs and Python syntax; application NOT tested.
|
||||
@@ -0,0 +1,26 @@
|
||||
docker compose --profile tools run --rm db-test
|
||||
Container mtusi-lab2-postgres-1 Running
|
||||
Container mtusi-lab2-valkey-1 Running
|
||||
Container mtusi-lab2-valkey-1 Waiting
|
||||
Container mtusi-lab2-postgres-1 Waiting
|
||||
Container mtusi-lab2-postgres-1 Healthy
|
||||
Container mtusi-lab2-valkey-1 Healthy
|
||||
Container mtusi-lab2-db-test-run-a1c49274ce09 Creating
|
||||
Container mtusi-lab2-db-test-run-a1c49274ce09 Created
|
||||
test_concurrent_registration_has_one_winner (test_store.StoreIntegrationTest.test_concurrent_registration_has_one_winner) ...
|
||||
20 параллельных create_user: 1 создан, 19 получили Conflict (409)
|
||||
ok
|
||||
test_create_chat_rolls_back_when_failing_midway (test_store.StoreIntegrationTest.test_create_chat_rolls_back_when_failing_midway) ...
|
||||
чат с несуществующим участником: транзакция откатилась, строк chats/chat_members не осталось
|
||||
ok
|
||||
test_database_rejects_message_from_non_member (test_store.StoreIntegrationTest.test_database_rejects_message_from_non_member) ...
|
||||
INSERT сообщения от не-участника напрямую в БД: ForeignKeyViolation
|
||||
ok
|
||||
test_migrations_rerun_is_noop (test_store.StoreIntegrationTest.test_migrations_rerun_is_noop) ...
|
||||
schema_migrations: ['001_core', '002_sessions']; повторный migrate() ничего не применил
|
||||
ok
|
||||
|
||||
----------------------------------------------------------------------
|
||||
Ran 4 tests in 0.120s
|
||||
|
||||
OK
|
||||
@@ -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-postgres-1 Waiting
|
||||
Container mtusi-lab2-valkey-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
|
||||
@@ -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
|
||||
----------------+----------------------
|
||||
21618 | 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.018..0.041 rows=51 loops=1)
|
||||
Buffers: shared hit=5
|
||||
-> Index Scan using messages_chat_history_idx on messages (actual time=0.017..0.033 rows=51 loops=1)
|
||||
Index Cond: (chat_id = '4981747a-a263-417e-80a3-fb7063eb8be5'::uuid)
|
||||
Buffers: shared hit=5
|
||||
Planning:
|
||||
Buffers: shared hit=6
|
||||
Planning Time: 0.139 ms
|
||||
Execution Time: 0.066 ms
|
||||
|
||||
|
||||
=== 2. Страница из середины истории по keyset-курсору (после 6000-го сообщения)
|
||||
QUERY PLAN
|
||||
------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
|
||||
Limit (actual time=0.009..0.020 rows=51 loops=1)
|
||||
Buffers: shared hit=4
|
||||
-> Index Scan using messages_chat_history_idx on messages (actual time=0.009..0.016 rows=51 loops=1)
|
||||
Index Cond: ((chat_id = '4981747a-a263-417e-80a3-fb7063eb8be5'::uuid) AND (ROW(created_at, id) > ROW('2026-01-01 01:40:00+00'::timestamp with time zone, '41b24ea4-c9d1-467e-a5cc-6b4a5413a8be'::uuid)))
|
||||
Buffers: shared hit=4
|
||||
Planning Time: 0.068 ms
|
||||
Execution Time: 0.076 ms
|
||||
|
||||
|
||||
=== 3. Для сравнения: та же страница через OFFSET (так приложение НЕ делает)
|
||||
QUERY PLAN
|
||||
-----------------------------------------------------------------------------------------------------------
|
||||
Limit (actual time=1.377..1.386 rows=51 loops=1)
|
||||
Buffers: shared hit=161
|
||||
-> Index Scan using messages_chat_history_idx on messages (actual time=0.023..1.131 rows=6051 loops=1)
|
||||
Index Cond: (chat_id = '4981747a-a263-417e-80a3-fb7063eb8be5'::uuid)
|
||||
Buffers: shared hit=161
|
||||
Planning Time: 0.099 ms
|
||||
Execution Time: 1.406 ms
|
||||
|
||||
|
||||
=== 4. Для сравнения: запрос 2 без индекса (индекс удалён только внутри этой транзакции)
|
||||
QUERY PLAN
|
||||
--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
|
||||
Limit (actual time=2.522..2.528 rows=51 loops=1)
|
||||
Buffers: shared hit=296
|
||||
-> Sort (actual time=2.522..2.524 rows=51 loops=1)
|
||||
Sort Key: created_at, id
|
||||
Sort Method: top-N heapsort Memory: 31kB
|
||||
Buffers: shared hit=296
|
||||
-> Seq Scan on messages (actual time=0.631..2.057 rows=6000 loops=1)
|
||||
Filter: ((chat_id = '4981747a-a263-417e-80a3-fb7063eb8be5'::uuid) AND (ROW(created_at, id) > ROW('2026-01-01 01:40:00+00'::timestamp with time zone, '41b24ea4-c9d1-467e-a5cc-6b4a5413a8be'::uuid)))
|
||||
Rows Removed by Filter: 15618
|
||||
Buffers: shared hit=296
|
||||
Planning:
|
||||
Buffers: shared hit=4
|
||||
Planning Time: 0.128 ms
|
||||
Execution Time: 2.554 ms
|
||||
|
||||
|
||||
=== ROLLBACK: синтетические данные удалены, индекс на месте
|
||||
@@ -0,0 +1,12 @@
|
||||
python student-tests/dependency_failure.py postgres
|
||||
stopping postgres (docker compose stop postgres)
|
||||
/health/live -> 200: процесс жив
|
||||
/health/ready -> 503 (1000 ms): без PostgreSQL обслуживать нельзя
|
||||
бизнес-запросы с действующим токеном -> 503 unavailable (без SQL и stack trace в ответе)
|
||||
без токена -> 401: аноним не становится доверенным
|
||||
неизвестный токен -> 503: не подтверждается ни кэшем, ни базой
|
||||
вход -> 503: сессию без базы не выдаём
|
||||
регистрация -> 503
|
||||
starting postgres again
|
||||
after recovery: прежний токен работает, подтверждённые сообщения на месте
|
||||
PASS: postgres outage handled without trusting anonymous requests
|
||||
@@ -0,0 +1,12 @@
|
||||
python student-tests/dependency_failure.py valkey
|
||||
stopping valkey (docker compose stop valkey)
|
||||
/health/ready -> 200 (16 ms): Valkey не критичен, API готов
|
||||
existing token: GET /users/me -> 200 (4015 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 31 ms (повторные попытки — в фоне)
|
||||
starting valkey again
|
||||
after recovery: прежний токен работает, подтверждённые сообщения на месте
|
||||
PASS: valkey outage handled without trusting anonymous requests
|
||||
@@ -0,0 +1,21 @@
|
||||
docker compose ps -a --format "table {{.Service}}\t{{.ID}}\t{{.Status}}"
|
||||
SERVICE CONTAINER ID STATUS
|
||||
api 08b92853bbb4 Up 3 minutes (healthy)
|
||||
api-short-ttl 047512285fe6 Up About a minute (healthy)
|
||||
postgres 094d2f567e2e Up 49 seconds (healthy)
|
||||
valkey 195f4a7b30f1 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.
|
||||
|
||||
real 0m11.081s
|
||||
user 0m0.015s
|
||||
sys 0m0.000s
|
||||
docker compose ps -a --format "table {{.Service}}\t{{.ID}}\t{{.Status}}"
|
||||
SERVICE CONTAINER ID STATUS
|
||||
api 08b92853bbb4 Up 2 seconds (health: starting)
|
||||
api-short-ttl 047512285fe6 Up About a minute (healthy)
|
||||
postgres 094d2f567e2e Up 8 seconds (healthy)
|
||||
valkey 195f4a7b30f1 Up 8 seconds (healthy)
|
||||
api-1 | 2026-10-09 10:18:10,200 INFO messenger.db: Миграции применены: 001_core, 002_sessions
|
||||
api-1 | 2026-10-09 10:21:37,443 INFO messenger.db: Миграции: новых нет, схема актуальна
|
||||
@@ -0,0 +1,6 @@
|
||||
python student-tests/race.py
|
||||
messages: sent 100 from 10 parallel clients in 0.97s
|
||||
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
|
||||
@@ -0,0 +1,16 @@
|
||||
Docker version 29.6.2, build dfc4efb
|
||||
Docker Compose version v5.3.1
|
||||
CONTAINER REPOSITORY TAG PLATFORM IMAGE ID SIZE CREATED
|
||||
mtusi-lab2-api-1 mtusi-messenger lab2 linux/amd64 22006a69bb96 57.7MB 50 seconds ago
|
||||
mtusi-lab2-postgres-1 postgres 17.10-bookworm linux/amd64 9b18b7839705 156MB 2 months ago
|
||||
mtusi-lab2-valkey-1 valkey/valkey 8.1.9 linux/amd64 d5e642b89ee0 46MB 5 weeks ago
|
||||
docker compose ps -a --format "table {{.Service}}\t{{.ID}}\t{{.Status}}"
|
||||
SERVICE CONTAINER ID STATUS
|
||||
api 08b92853bbb4 Up 39 seconds (healthy)
|
||||
postgres 094d2f567e2e Up 46 seconds (healthy)
|
||||
valkey 195f4a7b30f1 Up 46 seconds (healthy)
|
||||
api-1 | 2026-10-09 10:18:10,200 INFO messenger.db: Миграции применены: 001_core, 002_sessions
|
||||
uid=10001(app) gid=999(app) groups=999(app)
|
||||
$argon2id$v=19$m=19456,t=2,p=1
|
||||
.gitignore:2:.env .env
|
||||
.gitignore:5:secrets/ secrets/database_url
|
||||
@@ -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.181s
|
||||
|
||||
OK
|
||||
@@ -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.
|
||||
@@ -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
|
||||
|
||||
Reference in New Issue
Block a user