forked from mtusi2026/mtusi2026lab2
ЛР 2: PostgreSQL, сессии Basic/Bearer, Redis-кэш, тесты и отчёт
This commit is contained in:
@@ -0,0 +1,8 @@
|
||||
# 2026-10-15T10:02Z, второй экземпляр API с SESSION_TTL_SECONDS=2 (в compose: api-ttl на 8081)
|
||||
$ python student-tests/expiry.py
|
||||
ok - login -> 201
|
||||
ok - expires_at is about 2s ahead (got 2.00s)
|
||||
ok - token works before expiry
|
||||
ok - expired token -> 401 (cache does not extend the session)
|
||||
|
||||
4 passed, 0 failed
|
||||
@@ -0,0 +1,57 @@
|
||||
BEGIN
|
||||
INSERT 0 1
|
||||
INSERT 0 10
|
||||
INSERT 0 10
|
||||
INSERT 0 60000
|
||||
ANALYZE
|
||||
messages_in_target_chat
|
||||
-------------------------
|
||||
12000
|
||||
(1 row)
|
||||
|
||||
=== 1. Первая страница (limit 50 + 1) ===
|
||||
QUERY PLAN
|
||||
------------------------------------------------------------------------------------------------------------------------------------------------------
|
||||
Limit (cost=0.41..14.11 rows=51 width=65) (actual time=0.010..0.018 rows=51 loops=1)
|
||||
Buffers: shared hit=4
|
||||
-> Index Scan using messages_chat_created_id_idx on messages (cost=0.41..3252.33 rows=12114 width=65) (actual time=0.010..0.014 rows=51 loops=1)
|
||||
Index Cond: (chat_id = '00000000-0000-4000-8000-000000000100'::uuid)
|
||||
Buffers: shared hit=4
|
||||
Planning:
|
||||
Buffers: shared hit=18
|
||||
Planning Time: 0.107 ms
|
||||
Execution Time: 0.032 ms
|
||||
(9 rows)
|
||||
|
||||
=== 2. Страница из середины истории (keyset-курсор после ~6000-го сообщения) ===
|
||||
QUERY PLAN
|
||||
--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
|
||||
Limit (cost=0.42..15.40 rows=51 width=65) (actual time=0.012..0.035 rows=51 loops=1)
|
||||
Buffers: shared hit=5
|
||||
-> Index Scan using messages_chat_created_id_idx on messages (cost=0.42..3199.66 rows=10891 width=65) (actual time=0.011..0.030 rows=51 loops=1)
|
||||
Index Cond: ((chat_id = '00000000-0000-4000-8000-000000000100'::uuid) AND (ROW(created_at, id) > ROW(((now() - '1 day'::interval) + '00:00:06'::interval), '00000000-0000-0000-0000-000000000000'::uuid)))
|
||||
Buffers: shared hit=5
|
||||
Planning Time: 0.079 ms
|
||||
Execution Time: 0.094 ms
|
||||
(7 rows)
|
||||
|
||||
=== 3. Для сравнения: та же страница, если запретить индекс ===
|
||||
SET
|
||||
SET
|
||||
QUERY PLAN
|
||||
----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
|
||||
Limit (cost=2603.40..2603.52 rows=51 width=65) (actual time=6.820..6.826 rows=51 loops=1)
|
||||
Buffers: shared hit=740
|
||||
-> Sort (cost=2603.40..2630.62 rows=10891 width=65) (actual time=6.819..6.821 rows=51 loops=1)
|
||||
Sort Key: created_at, id
|
||||
Sort Method: top-N heapsort Memory: 31kB
|
||||
Buffers: shared hit=740
|
||||
-> Seq Scan on messages (cost=0.00..2240.05 rows=10891 width=65) (actual time=1.638..6.339 rows=6001 loops=1)
|
||||
Filter: ((chat_id = '00000000-0000-4000-8000-000000000100'::uuid) AND (ROW(created_at, id) > ROW(((now() - '1 day'::interval) + '00:00:06'::interval), '00000000-0000-0000-0000-000000000000'::uuid)))
|
||||
Rows Removed by Filter: 54001
|
||||
Buffers: shared hit=740
|
||||
Planning Time: 0.072 ms
|
||||
Execution Time: 6.841 ms
|
||||
(12 rows)
|
||||
|
||||
ROLLBACK
|
||||
@@ -0,0 +1,17 @@
|
||||
{
|
||||
"lab": 2,
|
||||
"workload": "closed-loop POST messages; no automatic retries",
|
||||
"requested_duration_seconds": 15.0,
|
||||
"elapsed_seconds": 15.11,
|
||||
"concurrency": 4,
|
||||
"successful_requests": 6636,
|
||||
"failed_requests": 0,
|
||||
"error_ratio": 0.0,
|
||||
"successful_rps": 439.183,
|
||||
"successful_latency_ms": {
|
||||
"p50": 8.483,
|
||||
"p95": 13.092,
|
||||
"p99": 17.662
|
||||
},
|
||||
"note": "Latency percentiles cover successes only. Timeouts/errors are counted separately; closed-loop has coordinated omission and client overhead."
|
||||
}
|
||||
@@ -0,0 +1,37 @@
|
||||
# 2026-10-15T09:59Z повторный запуск миграций на заполненной БД
|
||||
$ python -m app.migrate
|
||||
applied: nothing (up to date)
|
||||
$ psql: SELECT version, applied_at FROM schema_migrations; SELECT count(*) FROM users
|
||||
version | applied_at
|
||||
-----------+------------------------------
|
||||
0001_init | 2026-10-15 12:50:12.87179+03
|
||||
(1 row)
|
||||
|
||||
users
|
||||
-------
|
||||
46
|
||||
(1 row)
|
||||
|
||||
$ python -m app.migrate (ещё раз)
|
||||
applied: nothing (up to date)
|
||||
users
|
||||
-------
|
||||
46
|
||||
(1 row)
|
||||
|
||||
|
||||
# миграции с нуля на пустой БД
|
||||
$ DATABASE_URL=.../fresh python -m app.migrate
|
||||
INFO:messenger.migrate:migration applied: 0001_init
|
||||
applied: ['0001_init']
|
||||
List of relations
|
||||
Schema | Name | Type | Owner
|
||||
--------+-------------------+-------+-----------
|
||||
public | chat_members | table | messenger
|
||||
public | chats | table | messenger
|
||||
public | messages | table | messenger
|
||||
public | schema_migrations | table | messenger
|
||||
public | sessions | table | messenger
|
||||
public | users | table | messenger
|
||||
(6 rows)
|
||||
|
||||
@@ -0,0 +1,21 @@
|
||||
# 2026-10-15T10:02Z, локальный стенд; в Docker тот же скрипт по умолчанию делает docker compose stop/start
|
||||
== 1. Redis недоступен ==
|
||||
$ redis-cli shutdown nosave
|
||||
ok - valid token still works without Redis (cache bypassed)
|
||||
ok - writes still work without Redis
|
||||
ok - login works without Redis
|
||||
ok - forged token still rejected without Redis
|
||||
$ redis-server --daemonize yes --save '' --appendonly no
|
||||
== 2. PostgreSQL недоступен ==
|
||||
$ su postgres -c '/usr/lib/postgresql/16/bin/pg_ctl -D /tmp/pgdata -m fast -w stop'
|
||||
ok - history without DB -> 503, not a hang (got 503)
|
||||
ok - unknown token is never trusted without DB (got 503)
|
||||
ok - anonymous request -> 401
|
||||
ok - /health/ready -> 503
|
||||
ok - /health/live -> 200 (process is alive)
|
||||
$ su postgres -c '/usr/lib/postgresql/16/bin/pg_ctl -D /tmp/pgdata -w start -o "-p 5432 -k /tmp" -l /tmp/pg.log'
|
||||
== 3. восстановление ==
|
||||
ok - /health/ready back to 200
|
||||
ok - same token reads the same history after DB is back
|
||||
|
||||
11 passed, 0 failed
|
||||
@@ -0,0 +1,15 @@
|
||||
# 2026-10-15T10:02Z
|
||||
# hook: локальный аналог scripts/restart.sh (Docker недоступен на стенде): остановка API, pg_ctl restart PostgreSQL, перезапуск Redis, старт API; каталоги данных сохраняются
|
||||
$ python tests/resilience.py --mode persistence --action-script <hook>
|
||||
Executing explicit persistence hook; hook output suppressed to avoid leaking secrets.
|
||||
PASS: persistence preserved confirmed data and existing session. Hook scope needs operator evidence.
|
||||
|
||||
# процессы до/после (PID меняются => реально перезапущены):
|
||||
before:
|
||||
14201 python3 -m app
|
||||
14621 redis-server *:6379
|
||||
14632 /usr/lib/postgresql/16/bin/postgres -D /tmp/pgdata -p 5432 -k /tmp
|
||||
after:
|
||||
14958 /usr/lib/postgresql/16/bin/postgres -p 5432 -k /tmp
|
||||
14968 redis-server *:6379
|
||||
14975 python3 -m app
|
||||
@@ -0,0 +1,5 @@
|
||||
# 2026-10-15T10:02Z
|
||||
$ python student-tests/rollback_check.py
|
||||
ok - insert of unknown member failed on foreign key
|
||||
ok - after rollback: chats=0, members=0 (expected 0, 0)
|
||||
PASS
|
||||
@@ -0,0 +1,7 @@
|
||||
# 2026-10-15T10:02Z, local stand (PostgreSQL 16, Redis 7, Python 3.11), API http://127.0.0.1:8092
|
||||
$ make check
|
||||
PASS: offline skeleton structure, local refs and Python syntax; application NOT tested.
|
||||
$ make validate
|
||||
PASS: full OpenAPI 3.1 and JSON Schema validation; application NOT tested.
|
||||
$ make test
|
||||
PASS: lab2 public API scenario; infrastructure and grading evidence remain separate.
|
||||
@@ -0,0 +1,34 @@
|
||||
# 2026-10-15T10:02Z
|
||||
$ python student-tests/run.py
|
||||
== аутентификация ==
|
||||
ok - wrong password -> 401 + Basic challenge
|
||||
ok - unknown user -> 401 (same as wrong password)
|
||||
ok - no token -> 401 + Bearer challenge
|
||||
ok - X-User-Id alone gives no access
|
||||
ok - unknown/forged token -> 401
|
||||
ok - Basic on business endpoint -> 401
|
||||
ok - X-User-Id cannot override bearer identity
|
||||
ok - password shorter than 12 -> 400
|
||||
== logout ==
|
||||
ok - logout -> 204
|
||||
ok - token after logout -> 401
|
||||
ok - second logout -> 401
|
||||
== гонка регистрации одного username ==
|
||||
ok - 20 parallel registrations -> one 201, nineteen 409 (got [201, 409, 409, 409, 409, 409, 409, 409, 409, 409, 409, 409, 409, 409, 409, 409, 409, 409, 409, 409])
|
||||
== ошибки и доступ (из lab1) ==
|
||||
ok - malformed JSON -> 400
|
||||
ok - duplicate username -> 409
|
||||
ok - blank message -> 400
|
||||
ok - sender_id in body is rejected
|
||||
ok - outsider POST to foreign chat -> 404
|
||||
ok - outsider GET foreign history -> 404
|
||||
ok - invalid chat uuid -> 400
|
||||
== пагинация ==
|
||||
ok - 5 messages / limit 2 -> 3 pages, no duplicates
|
||||
ok - cursor from another chat -> 400
|
||||
|
||||
21 passed, 0 failed
|
||||
|
||||
$ python student-tests/race.py
|
||||
sent=100 accepted=100 received=100 unique_ids=100 all_texts_present=True
|
||||
PASS
|
||||
Reference in New Issue
Block a user