Заполнить отчёт и добавить доказательства

This commit is contained in:
2026-10-08 18:58:37 +03:00
parent 6473fd06e9
commit 36ad7a4f5a
9 changed files with 617 additions and 14 deletions
+72
View File
@@ -0,0 +1,72 @@
# Запуск из чистого clone на пустых volumes, публичный smoke
# дата: 2026-10-08T15:55Z, commit: 6473fd0
# стенд: Apple M3 Pro, 11 CPU, 18 GB RAM, macOS 26.1, Docker 29.3.0, Compose 5.1.0
$ ./scripts/init-env.sh
пароли записаны в .env
$ docker compose --env-file .env config --quiet
$ docker compose --env-file .env up -d --build
Image mtusi-messenger:lab2 Built
Image mtusi-messenger:lab2 Built
Network mtusi-messenger-lab2_default Creating
Network mtusi-messenger-lab2_default Created
Volume mtusi-messenger-lab2_redisdata Creating
Volume mtusi-messenger-lab2_redisdata Created
Volume mtusi-messenger-lab2_pgdata Creating
Volume mtusi-messenger-lab2_pgdata Created
Container mtusi-messenger-lab2-postgres-1 Creating
Container mtusi-messenger-lab2-redis-1 Creating
Container mtusi-messenger-lab2-postgres-1 Created
Container mtusi-messenger-lab2-redis-1 Created
Container mtusi-messenger-lab2-migrate-1 Creating
Container mtusi-messenger-lab2-migrate-1 Created
Container mtusi-messenger-lab2-api-1 Creating
Container mtusi-messenger-lab2-api-1 Created
Container mtusi-messenger-lab2-postgres-1 Starting
Container mtusi-messenger-lab2-redis-1 Starting
Container mtusi-messenger-lab2-postgres-1 Started
Container mtusi-messenger-lab2-postgres-1 Waiting
Container mtusi-messenger-lab2-redis-1 Started
Container mtusi-messenger-lab2-postgres-1 Healthy
Container mtusi-messenger-lab2-migrate-1 Starting
Container mtusi-messenger-lab2-migrate-1 Started
Container mtusi-messenger-lab2-migrate-1 Waiting
Container mtusi-messenger-lab2-redis-1 Waiting
Container mtusi-messenger-lab2-migrate-1 Exited
Container mtusi-messenger-lab2-redis-1 Healthy
Container mtusi-messenger-lab2-api-1 Starting
Container mtusi-messenger-lab2-api-1 Started
$ ./scripts/wait-ready.sh
готов: http://localhost:8080
$ docker compose --env-file .env ps -a
SERVICE IMAGE STATE STATUS
api mtusi-messenger:lab2 running Up 1 second (health: starting)
migrate mtusi-messenger:lab2 exited Exited (0) 1 second ago
postgres postgres:17.11-alpine running Up 7 seconds (healthy)
redis redis:7.4.11-alpine running Up 7 seconds (healthy)
$ docker compose --env-file .env logs migrate
migrate-1 | применена: 0001_init.sql
$ curl -s -i http://localhost:8080/health/ready
HTTP/1.1 200 OK
date: Thu, 08 Oct 2026 15:55:10 GMT
server: uvicorn
content-length: 15
content-type: application/json
x-request-id: c5fc87a41bdc4cfaa665cddb6d79a6c0
{"status":"ok"}
$ make check
python3 scripts/check_contract.py
PASS: offline skeleton structure, local refs and Python syntax; application NOT tested.
$ make test
python3 tests/smoke.py --base-url "http://localhost:8080"
PASS: lab2 public API scenario; infrastructure and grading evidence remain separate.
+73
View File
@@ -0,0 +1,73 @@
# Собственные тесты API
# дата: 2026-10-08T15:55Z, commit: 6473fd0
# стенд: Apple M3 Pro, 11 CPU, 18 GB RAM, macOS 26.1, Docker 29.3.0, Compose 5.1.0
$ make student-test
BASE_URL="http://localhost:8080" python3 -m unittest discover -s student-tests -v
test_blank_title (test_access.CreateChatTest.test_blank_title) ... ok
test_creator_must_be_member (test_access.CreateChatTest.test_creator_must_be_member) ... ok
test_duplicate_members (test_access.CreateChatTest.test_duplicate_members) ... ok
test_empty_members (test_access.CreateChatTest.test_empty_members) ... ok
test_failed_create_leaves_no_chat (test_access.CreateChatTest.test_failed_create_leaves_no_chat) ... ok
test_unknown_member (test_access.CreateChatTest.test_unknown_member) ... ok
test_bad_chat_id (test_access.ForeignChatTest.test_bad_chat_id) ... ok
test_chat_is_not_listed_for_outsider (test_access.ForeignChatTest.test_chat_is_not_listed_for_outsider) ... ok
test_foreign_chat_looks_like_missing_chat (test_access.ForeignChatTest.test_foreign_chat_looks_like_missing_chat) ... ok
test_members_can_read_and_write (test_access.ForeignChatTest.test_members_can_read_and_write) ... ok
test_outsider_gets_404_everywhere (test_access.ForeignChatTest.test_outsider_gets_404_everywhere) ... ok
test_outsider_message_is_not_saved (test_access.ForeignChatTest.test_outsider_message_is_not_saved) ... ok
test_basic_is_not_accepted_on_business_endpoints (test_auth.BearerTest.test_basic_is_not_accepted_on_business_endpoints) ... ok
test_no_token (test_auth.BearerTest.test_no_token) ... ok
test_token_is_checked_before_anything_else (test_auth.BearerTest.test_token_is_checked_before_anything_else) ... ok
test_unknown_tokens (test_auth.BearerTest.test_unknown_tokens) ... ok
test_x_user_id_does_not_change_identity (test_auth.BearerTest.test_x_user_id_does_not_change_identity) ... ok
test_x_user_id_gives_no_access (test_auth.BearerTest.test_x_user_id_gives_no_access) ... ok
test_colon_and_unicode_in_password (test_auth.LoginTest.test_colon_and_unicode_in_password) ... ok
test_login (test_auth.LoginTest.test_login) ... ok
test_malformed_credentials (test_auth.LoginTest.test_malformed_credentials) ... ok
test_token_is_opaque_and_unique (test_auth.LoginTest.test_token_is_opaque_and_unique) ... ok
test_username_that_cannot_exist (test_auth.LoginTest.test_username_that_cannot_exist) ... ok
test_wrong_password_and_unknown_user_look_the_same (test_auth.LoginTest.test_wrong_password_and_unknown_user_look_the_same) ... ok
test_login_again_after_logout (test_auth.LogoutTest.test_login_again_after_logout) ... ok
test_logout_requires_token (test_auth.LogoutTest.test_logout_requires_token) ... ok
test_logout_revokes_only_current_session (test_auth.LogoutTest.test_logout_revokes_only_current_session) ... ok
test_100_messages_from_10_clients (test_concurrency.ConcurrencyTest.test_100_messages_from_10_clients) ... ok
test_same_username_registered_once (test_concurrency.ConcurrencyTest.test_same_username_registered_once) ... ok
test_chat_cursor_belongs_to_user (test_pagination.ChatPaginationTest.test_chat_cursor_belongs_to_user) ... ok
test_walk_chat_list (test_pagination.ChatPaginationTest.test_walk_chat_list) ... ok
test_bad_cursor (test_pagination.MessagePaginationTest.test_bad_cursor) ... ok
test_bad_limit (test_pagination.MessagePaginationTest.test_bad_limit) ... ok
test_cursor_from_another_chat (test_pagination.MessagePaginationTest.test_cursor_from_another_chat) ... ok
test_default_limit (test_pagination.MessagePaginationTest.test_default_limit) ... ok
test_exact_page_has_no_cursor (test_pagination.MessagePaginationTest.test_exact_page_has_no_cursor) ... ok
test_limit_can_change_between_pages (test_pagination.MessagePaginationTest.test_limit_can_change_between_pages) ... ok
test_new_message_appears_after_last_page (test_pagination.MessagePaginationTest.test_new_message_appears_after_last_page) ... ok
test_no_duplicates_and_order (test_pagination.MessagePaginationTest.test_no_duplicates_and_order) ... ok
test_walk_several_pages (test_pagination.MessagePaginationTest.test_walk_several_pages) ... ok
test_extra_field (test_validation.InvalidJsonTest.test_extra_field) ... ok
test_malformed_json (test_validation.InvalidJsonTest.test_malformed_json) ... ok
test_malformed_json_in_message (test_validation.InvalidJsonTest.test_malformed_json_in_message) ... ok
test_missing_field (test_validation.InvalidJsonTest.test_missing_field) ... ok
test_not_an_object (test_validation.InvalidJsonTest.test_not_an_object) ... ok
test_wrong_type (test_validation.InvalidJsonTest.test_wrong_type) ... ok
test_empty_message (test_validation.MessageValidationTest.test_empty_message) ... ok
test_nul_character (test_validation.MessageValidationTest.test_nul_character) ... ok
test_sender_id_is_not_accepted (test_validation.MessageValidationTest.test_sender_id_is_not_accepted) ... ok
test_text_limit (test_validation.MessageValidationTest.test_text_limit) ... ok
test_unicode_is_kept (test_validation.MessageValidationTest.test_unicode_is_kept) ... ok
test_whitespace_message (test_validation.MessageValidationTest.test_whitespace_message) ... ok
test_bad_display_names (test_validation.UserValidationTest.test_bad_display_names) ... ok
test_bad_passwords (test_validation.UserValidationTest.test_bad_passwords) ... ok
test_bad_usernames (test_validation.UserValidationTest.test_bad_usernames) ... ok
test_display_name_length_is_counted_in_code_points (test_validation.UserValidationTest.test_display_name_length_is_counted_in_code_points) ... ok
test_duplicate_username (test_validation.UserValidationTest.test_duplicate_username) ... ok
test_password_is_never_returned (test_validation.UserValidationTest.test_password_is_never_returned) ... ok
test_password_length_limits (test_validation.UserValidationTest.test_password_length_limits) ... ok
----------------------------------------------------------------------
Ran 59 tests in 1.690s
OK
отправлено 100, подтверждено 100, в истории 100, уникальных id 100
+46
View File
@@ -0,0 +1,46 @@
# Сохранность: перезапуск API, PostgreSQL и Redis с сохранением volumes
# дата: 2026-10-08T15:55Z, commit: 6473fd0
# стенд: Apple M3 Pro, 11 CPU, 18 GB RAM, macOS 26.1, Docker 29.3.0, Compose 5.1.0
# до перезапуска
postgres StartedAt=2026-10-08T15:55:04.230004924Z
redis StartedAt=2026-10-08T15:55:04.230356549Z
api StartedAt=2026-10-08T15:55:10.436053969Z
$ cat scripts/restart.sh
#!/bin/sh
# Перезапускает API и оба хранилища. Volumes не трогает: данные и сессии должны остаться.
set -eu
cd "$(dirname "$0")/.."
docker compose --env-file .env restart postgres redis api
$ 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.
# после перезапуска: у всех трёх контейнеров новое время старта
postgres StartedAt=2026-10-08T15:55:15.070657346Z
redis StartedAt=2026-10-08T15:55:15.160837596Z
api StartedAt=2026-10-08T15:55:15.392988013Z
$ docker volume ls --filter name=mtusi-messenger-lab2
DRIVER VOLUME NAME
local mtusi-messenger-lab2_pgdata
local mtusi-messenger-lab2_redisdata
# повторный запуск миграций
$ docker compose --env-file .env run --rm migrate
Container mtusi-messenger-lab2-postgres-1 Running
Container mtusi-messenger-lab2-postgres-1 Waiting
Container mtusi-messenger-lab2-postgres-1 Healthy
Container mtusi-messenger-lab2-migrate-run-c47ffc8919e4 Creating
Container mtusi-messenger-lab2-migrate-run-c47ffc8919e4 Created
уже применена: 0001_init.sql
$ psql: SELECT * FROM schema_migrations
version | applied_at
---------------+-------------------------------
0001_init.sql | 2026-10-08 15:55:10.184216+00
(1 row)
+36
View File
@@ -0,0 +1,36 @@
# Сессии в Redis: настройки persistence, вид ключа, TTL не продлевается перезапуском
# дата: 2026-10-08T15:55Z, commit: 6473fd0
# стенд: Apple M3 Pro, 11 CPU, 18 GB RAM, macOS 26.1, Docker 29.3.0, Compose 5.1.0
$ redis-cli CONFIG GET appendonly / appendfsync / maxmemory-policy
appendonly
yes
appendfsync
always
maxmemory-policy
noeviction
$ redis-cli --scan --pattern 'session:*' | wc -l
41
# один из ключей: sha256 от токена, значение — id пользователя
$ redis-cli GET session:e478544e3e6f92c4c36896617f812541bdb171df4654de1fafaad9074c962367
97dbb54c-2e55-441f-ae31-ef469b935758
$ redis-cli TTL session:e478544e3e6f92c4c36896617f812541bdb171df4654de1fafaad9074c962367
3591
$ docker compose --env-file .env restart redis
Container mtusi-messenger-lab2-redis-1 Restarting
Container mtusi-messenger-lab2-redis-1 Started
$ redis-cli TTL session:e478544e3e6f92c4c36896617f812541bdb171df4654de1fafaad9074c962367 # после перезапуска ключ на месте, TTL уменьшился
3583
$ docker compose --env-file .env exec -T redis ls -la /data/appendonlydir
total 24
drwx------ 2 redis redis 4096 Oct 8 15:55 .
drwxr-xr-x 3 redis redis 4096 Oct 8 15:55 ..
-rw------- 1 redis redis 89 Oct 8 15:55 appendonly.aof.1.base.rdb
-rw------- 1 redis redis 7582 Oct 8 15:55 appendonly.aof.1.incr.aof
-rw------- 1 redis redis 88 Oct 8 15:55 appendonly.aof.manifest
+36
View File
@@ -0,0 +1,36 @@
# Тесты отказов: истечение сессии, остановка Redis и PostgreSQL, откат транзакции, гонка регистрации
# дата: 2026-10-08T15:55Z, commit: 6473fd0
# стенд: Apple M3 Pro, 11 CPU, 18 GB RAM, macOS 26.1, Docker 29.3.0, Compose 5.1.0
$ make test-failures
BASE_URL="http://localhost:8080" python3 -m unittest discover -s student-tests/failures -v
test_postgres_down (test_dependencies.DependencyDownTest.test_postgres_down) ... ok
test_redis_down (test_dependencies.DependencyDownTest.test_redis_down) ... ok
test_expires_at_matches_ttl (test_expiry.SessionExpiryTest.test_expires_at_matches_ttl) ... ok
test_login_after_expiry (test_expiry.SessionExpiryTest.test_login_after_expiry) ... ok
test_requests_do_not_extend_session (test_expiry.SessionExpiryTest.test_requests_do_not_extend_session) ... ok
test_session_expires (test_expiry.SessionExpiryTest.test_session_expires) ... ok
test_chat_with_unknown_member_is_rolled_back (test_transactions.TransactionTest.test_chat_with_unknown_member_is_rolled_back) ... ok
test_migrations_can_be_repeated (test_transactions.TransactionTest.test_migrations_can_be_repeated) ... ok
test_password_is_stored_as_argon2id_hash (test_transactions.TransactionTest.test_password_is_stored_as_argon2id_hash) ... ok
test_username_race_creates_one_row (test_transactions.TransactionTest.test_username_race_creates_one_row) ... ok
test_valid_chat_is_committed_whole (test_transactions.TransactionTest.test_valid_chat_is_committed_whole) ... ok
----------------------------------------------------------------------
Ran 11 tests in 47.384s
OK
# время ответа при отказе (после тестов сервисы снова остановлены вручную)
$ docker compose stop redis; curl /api/v1/users/me с Bearer-токеном
{"error":{"code":"unavailable","message":"Сервис временно недоступен","request_id":"ec599bbf80da42ba9410d2bb5fe44408"}}
HTTP 503 за 0.010007 с
$ docker compose stop postgres; curl /health/ready
{"error":{"code":"unavailable","message":"Сервис временно недоступен","request_id":"ff86a9409ca74d1a9207d7efe82e4313"}}
HTTP 503 за 3.015225 с
$ docker compose logs api | grep unavailable | tail -4
api-1 | 2026-10-08 15:55:59,645 WARNING messenger: redis unavailable: ConnectionError request_id=7303c9edcbe8408496ff607945e71893
api-1 | 2026-10-08 15:55:59,653 WARNING messenger: redis unavailable: ConnectionError request_id=0a217c1035f548f0b3a68b9bb0640d3f
api-1 | 2026-10-08 15:56:17,960 WARNING messenger: redis unavailable: ConnectionError request_id=ec599bbf80da42ba9410d2bb5fe44408
api-1 | 2026-10-08 15:56:21,270 WARNING messenger: postgres unavailable: PoolTimeout request_id=ff86a9409ca74d1a9207d7efe82e4313
+74
View File
@@ -0,0 +1,74 @@
# Индекс истории: EXPLAIN (ANALYZE, BUFFERS) на 60 000 сообщений, 10 000 в одном чате
# дата: 2026-10-08T15:56Z, commit: 6473fd0
# стенд: Apple M3 Pro, 11 CPU, 18 GB RAM, macOS 26.1, Docker 29.3.0, Compose 5.1.0
$ make explain
./scripts/explain_history.sh
== Объём данных
messages_total | messages_in_chat | table_size | index_size
----------------+------------------+------------+------------
60140 | 10000 | 6848 kB | 6160 kB
(1 row)
== 1. Первая страница (limit 50, запрос берёт 51 строку)
QUERY PLAN
---------------------------------------------------------------------------------------------------------------------------------------------------
Limit (cost=0.41..21.21 rows=51 width=80) (actual time=0.007..0.015 rows=51 loops=1)
Buffers: shared hit=8
-> Index Scan using messages_chat_history_idx on messages (cost=0.41..4114.85 rows=10089 width=80) (actual time=0.006..0.012 rows=51 loops=1)
Index Cond: (chat_id = '00000000-0000-4000-8000-000000000100'::uuid)
Buffers: shared hit=8
Planning:
Buffers: shared hit=33
Planning Time: 0.079 ms
Execution Time: 0.025 ms
(9 rows)
== 2. Страница из середины истории: keyset после 5000-го сообщения
QUERY PLAN
-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
Limit (cost=0.41..38.79 rows=51 width=80) (actual time=0.006..0.015 rows=51 loops=1)
Buffers: shared hit=8
-> Index Scan using messages_chat_history_idx on messages (cost=0.41..3778.58 rows=5021 width=80) (actual time=0.006..0.012 rows=51 loops=1)
Index Cond: ((chat_id = '00000000-0000-4000-8000-000000000100'::uuid) AND (ROW(created_at, id) > ROW('2026-10-08 07:36:22.289031+00'::timestamp with time zone, '31ba47ee-c105-47bd-9bb1-79986700dbd4'::uuid)))
Buffers: shared hit=8
Planning Time: 0.031 ms
Execution Time: 0.034 ms
(7 rows)
== 3. Та же страница через OFFSET (так делать не стали)
QUERY PLAN
-----------------------------------------------------------------------------------------------------------------------------------------------------
Limit (cost=2039.48..2060.28 rows=51 width=80) (actual time=0.459..0.464 rows=51 loops=1)
Buffers: shared hit=491
-> Index Scan using messages_chat_history_idx on messages (cost=0.41..4114.85 rows=10089 width=80) (actual time=0.005..0.359 rows=5051 loops=1)
Index Cond: (chat_id = '00000000-0000-4000-8000-000000000100'::uuid)
Buffers: shared hit=491
Planning Time: 0.016 ms
Execution Time: 0.469 ms
(7 rows)
== 4. Запрос из пункта 2 без индекса messages_chat_history_idx (DROP INDEX внутри транзакции с ROLLBACK)
QUERY PLAN
---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
Limit (cost=2075.96..2076.09 rows=51 width=80) (actual time=2.252..2.256 rows=51 loops=1)
Buffers: shared hit=862
-> Sort (cost=2075.96..2088.51 rows=5021 width=80) (actual time=2.252..2.254 rows=51 loops=1)
Sort Key: created_at, id
Sort Method: top-N heapsort Memory: 31kB
Buffers: shared hit=862
-> Seq Scan on messages (cost=0.00..1908.45 rows=5021 width=80) (actual time=0.939..2.012 rows=5000 loops=1)
Filter: ((chat_id = '00000000-0000-4000-8000-000000000100'::uuid) AND (ROW(created_at, id) > ROW('2026-10-08 07:36:22.289031+00'::timestamp with time zone, '31ba47ee-c105-47bd-9bb1-79986700dbd4'::uuid)))
Rows Removed by Filter: 55140
Buffers: shared hit=856
Planning:
Buffers: shared hit=4
Planning Time: 0.032 ms
Execution Time: 2.266 ms
(14 rows)
+58
View File
@@ -0,0 +1,58 @@
# Контейнеры: пользователи, секреты, версии
# дата: 2026-10-08T15:56Z, commit: 6473fd0
# стенд: Apple M3 Pro, 11 CPU, 18 GB RAM, macOS 26.1, Docker 29.3.0, Compose 5.1.0
$ docker compose --env-file .env exec -T api id
uid=10001(app) gid=10001(app) groups=10001(app)
$ docker compose exec api ls -l /run/secrets
total 8
-r--r--r-- 1 root root 70 Oct 8 15:55 cache_url
-r--r--r-- 1 root root 95 Oct 8 15:55 database_url
$ docker compose exec api env | grep -ci "password\|postgresql://\|redis://" # секретов в окружении нет
0
$ docker compose exec redis ps -o user,args
USER COMMAND
redis redis-server *:6379
root ps -o user,args
$ docker compose exec postgres ps -o user,args | head -3
USER COMMAND
postgres postgres
postgres postgres: checkpointer
$ docker compose --env-file .env images
CONTAINER REPOSITORY TAG PLATFORM IMAGE ID SIZE CREATED
mtusi-messenger-lab2-api-1 mtusi-messenger lab2 linux/arm64 46505be4fa02 203MB 47 minutes ago
mtusi-messenger-lab2-migrate-1 mtusi-messenger lab2 linux/arm64 46505be4fa02 203MB 47 minutes ago
mtusi-messenger-lab2-postgres-1 postgres 17.11-alpine linux/arm64/v8 25a89970a832 291MB 2 weeks ago
mtusi-messenger-lab2-redis-1 redis 7.4.11-alpine linux/arm64/v8 ec4f171e9ff0 39.5MB 2 weeks ago
$ docker compose --env-file .env exec -T api pip freeze --disable-pip-version-check
annotated-doc==0.0.5
annotated-types==0.8.0
anyio==4.15.1
argon2-cffi==25.1.0
argon2-cffi-bindings==26.1.0
cffi==2.1.1
click==8.5.0
fastapi==0.143.0
h11==0.16.0
idna==3.20
opentelemetry-api==1.45.1
psycopg==3.3.6
psycopg-binary==3.3.6
psycopg-pool==3.3.3
pycparser==3.1
pydantic==2.13.5
pydantic_core==2.46.5
redis==8.1.0
starlette==1.7.0
typing-inspection==0.4.4
typing_extensions==4.16.0
uvicorn==0.54.0
$ git ls-files | grep -E "^\.env$|secrets" # в Git секретов нет
(пусто)
+11
View File
@@ -0,0 +1,11 @@
# SIGTERM (возможность lab1 сохранена)
# дата: 2026-10-08T15:56Z, commit: 6473fd0
# стенд: Apple M3 Pro, 11 CPU, 18 GB RAM, macOS 26.1, Docker 29.3.0, Compose 5.1.0
$ python3 scripts/sigterm_check.py
$ docker kill --signal=SIGTERM <контейнер api>
новый запрос после SIGTERM: не принят (RemoteDisconnected)
начатый до SIGTERM запрос: HTTP/1.1 201 Created
процесс завершился за 1.45 с, код выхода 0
PASS: остановка корректная и укладывается в 10 секунд