ЛР 2: PostgreSQL, сессии в Valkey, трек 2
Application / app (pull_request) Canceled after 0s
Skeleton contracts / contracts (pull_request) Canceled after 0s

This commit is contained in:
alenchha
2026-10-19 19:11:28 +03:00
parent 65003b6119
commit 6bec450e20
50 changed files with 3210 additions and 14 deletions
+111
View File
@@ -0,0 +1,111 @@
"""Shared HTTP helpers for the student checks; stdlib only, Python 3.9+."""
import argparse
import base64
import json
import os
import sys
import urllib.error
import urllib.request
import uuid
DEFAULT_BASE = os.environ.get("BASE_URL", "http://localhost:8080")
class Failed(AssertionError):
pass
def expect(condition, message):
if not condition:
raise Failed(message)
def call(base, method, path, body=None, token=None, headers=None, timeout=10, raw=None, content_type=None):
sent = {"Accept": "application/json"}
data = raw
if body is not None:
data = json.dumps(body, ensure_ascii=False).encode("utf-8")
sent["Content-Type"] = "application/json"
if content_type is not None:
sent["Content-Type"] = content_type
if token:
sent["Authorization"] = "Bearer " + token
sent.update(headers or {})
request = urllib.request.Request(base + path, data=data, headers=sent, method=method)
try:
response = urllib.request.urlopen(request, timeout=timeout)
except urllib.error.HTTPError as error:
response = error
except (urllib.error.URLError, TimeoutError, OSError) as exc:
raise Failed("%s %s: нет соединения (%s)" % (method, path, type(exc).__name__)) from None
with response:
raw = response.read()
payload = None
if raw:
try:
payload = json.loads(raw)
except ValueError:
payload = None
return {"status": response.code, "headers": response.headers, "json": payload}
def credentials(label="check"):
return {
"username": "u_%s_%s" % (label, uuid.uuid4().hex[:10]),
"display_name": "Проверка " + label,
"password": "T3st-" + uuid.uuid4().hex,
}
def basic(username, password):
return "Basic " + base64.b64encode(("%s:%s" % (username, password)).encode("utf-8")).decode()
def register(base, label="check"):
body = credentials(label)
result = call(base, "POST", "/api/v1/users", body=body)
expect(result["status"] == 201, "регистрация вернула %s" % result["status"])
return {"registration": body, "user": result["json"], "id": result["json"]["id"]}
def login(base, actor):
result = call(
base,
"POST",
"/api/v1/auth/sessions",
headers={"Authorization": basic(actor["registration"]["username"], actor["registration"]["password"])},
)
expect(result["status"] == 201, "вход вернул %s" % result["status"])
actor["token"] = result["json"]["token"]
actor["session"] = result["json"]
return actor
def member(base, label="check"):
return login(base, register(base, label))
def chat_with(base, owner, *others):
members = [owner["id"]] + [other["id"] for other in others]
result = call(base, "POST", "/api/v1/chats", body={"title": "Проверка " + uuid.uuid4().hex[:8], "member_ids": members}, token=owner["token"])
expect(result["status"] == 201, "создание чата вернуло %s" % result["status"])
return result["json"]
def arguments(description):
parser = argparse.ArgumentParser(description=description)
parser.add_argument("--base-url", default=DEFAULT_BASE)
return parser.parse_args()
def run(tests, base):
failures = []
for test in tests:
try:
test(base)
print("PASS %s" % test.__name__)
except AssertionError as exc:
failures.append(test.__name__)
print("FAIL %s: %s" % (test.__name__, exc))
print("%d/%d checks passed" % (len(tests) - len(failures), len(tests)))
sys.exit(1 if failures else 0)
+39
View File
@@ -0,0 +1,39 @@
#!/bin/sh
set -eu
cd "$(dirname "$0")/.."
COMPOSE="docker compose --env-file .env"
wait_ready() {
i=0
while [ "$i" -lt 60 ]; do
if curl -fsS http://localhost:8080/health/ready >/dev/null 2>&1; then return 0; fi
i=$((i + 1))
sleep 1
done
echo "API не стал ready" >&2
return 1
}
restore() {
$COMPOSE start valkey postgres >/dev/null 2>&1 || true
}
trap restore EXIT
echo "=== 1. Останавливаю кэш сессий (valkey) ==="
$COMPOSE stop valkey
$COMPOSE ps --format '{{.Service}} {{.Status}}'
python3 student-tests/test_without_cache.py --base-url http://localhost:8080
$COMPOSE start valkey
wait_ready
echo
echo "=== 2. Останавливаю PostgreSQL ==="
$COMPOSE stop postgres
$COMPOSE ps --format '{{.Service}} {{.Status}}'
python3 student-tests/test_without_db.py --base-url http://localhost:8080
$COMPOSE start postgres
wait_ready
echo
echo "=== 3. Состояние восстановлено ==="
$COMPOSE ps --format '{{.Service}} {{.Status}}'
+126
View File
@@ -0,0 +1,126 @@
#!/bin/sh
set -eu
cd "$(dirname "$0")/.."
OUT=${OUT:-evidence}
TOTAL=${TOTAL:-120000}
COMPOSE="docker compose --env-file .env"
mkdir -p "$OUT" "$OUT/track2"
step() {
printf '\n######## %s ########\n' "$1"
}
wait_ready() {
i=0
while [ "$i" -lt 90 ]; do
if curl -fsS http://localhost:8080/health/ready >/dev/null 2>&1; then return 0; fi
i=$((i + 1))
sleep 1
done
echo "API не стал ready" >&2
return 1
}
step "0. Чистый стенд: удаляю том базы и поднимаю заново"
$COMPOSE down -v
$COMPOSE up -d --build
wait_ready
{
uname -sm
docker --version
$COMPOSE version
$COMPOSE ps --format '{{.Service}} {{.Image}} {{.Status}}'
$COMPOSE exec -T postgres psql -U messenger -d messenger -t -A -c 'select version()'
$COMPOSE exec -T valkey valkey-server --version
} > "$OUT/stand.txt" 2>&1
cat "$OUT/stand.txt"
step "1. Миграции с нуля и повторный запуск"
{
echo '--- первый запуск (из логов сервиса migrate) ---'
$COMPOSE logs migrate --tail=10
echo '--- повторный запуск ---'
$COMPOSE run --rm migrate
echo '--- схема ---'
$COMPOSE exec -T postgres psql -U messenger -d messenger -X -c '\d+ messages'
$COMPOSE exec -T postgres psql -U messenger -d messenger -X -c 'table schema_migrations'
} > "$OUT/migrations.txt" 2>&1
tail -5 "$OUT/migrations.txt"
step "2. Публичный smoke"
make test > "$OUT/smoke.txt" 2>&1
tail -1 "$OUT/smoke.txt"
step "3. Свои проверки уровня 4"
{
python3 student-tests/test_auth_sessions.py
echo
python3 student-tests/test_storage_rules.py
} > "$OUT/level4-tests.txt" 2>&1
grep 'checks passed' "$OUT/level4-tests.txt"
step "4. Истечение сессии при коротком TTL"
sh student-tests/expiry.sh > "$OUT/expiry.txt" 2>&1
grep 'checks passed' "$OUT/expiry.txt"
step "5. Отзыв сессии против кэша и зависшая БД"
python3 student-tests/test_outages.py > "$OUT/outages.txt" 2>&1
grep 'checks passed' "$OUT/outages.txt"
step "6. Отказ Valkey, затем отказ PostgreSQL"
sh student-tests/dependency.sh > "$OUT/dependency.txt" 2>&1
grep 'checks passed' "$OUT/dependency.txt"
step "7. Рестарт API и всех хранилищ"
{
echo '--- состояние контейнеров до рестарта ---'
$COMPOSE ps --format '{{.Service}} {{.Status}}'
} > "$OUT/persistence.txt" 2>&1
make test-persistence ACTION_SCRIPT=scripts/restart.sh >> "$OUT/persistence.txt" 2>&1
{
echo '--- состояние контейнеров после рестарта ---'
$COMPOSE ps --format '{{.Service}} {{.Status}}'
echo '--- логи postgres о перезапуске ---'
$COMPOSE logs postgres --tail=6
} >> "$OUT/persistence.txt" 2>&1
grep 'PASS\|FAIL' "$OUT/persistence.txt"
step "8. Нагрузка с кэшем сессий и без него"
python3 tests/load.py --duration 30 --concurrency 4 --output "$OUT/load-cache.json" > "$OUT/load.txt" 2>&1
$COMPOSE stop valkey
python3 tests/load.py --duration 30 --concurrency 4 --output "$OUT/load-nocache.json" >> "$OUT/load.txt" 2>&1
$COMPOSE start valkey
wait_ready
python3 - "$OUT" <<'PYEOF'
import json
import sys
out = sys.argv[1]
for name in ("load-cache", "load-nocache"):
with open(out + "/" + name + ".json") as handle:
data = json.load(handle)
print(name, data["successful_requests"], "ok,", data["failed_requests"], "fail,",
data["successful_rps"], "rps,", data["successful_latency_ms"])
PYEOF
step "9. План запроса истории"
make explain > "$OUT/explain-10k.txt" 2>&1
grep -E 'messages_total|Execution Time' "$OUT/explain-10k.txt" | head -8
step "10. Трек 5: индексы и восстановление"
TOTAL="$TOTAL" sh student-tests/track2.sh > "$OUT/track2/run.txt" 2>&1
grep -E 'backup_seconds|restore_seconds|RESULT|маркеров' "$OUT/track2/run.txt"
step "11. Гигиена репозитория"
{
git status --porcelain
echo '--- правила игнорирования ---'
git check-ignore -v .env secrets/database_url secrets/postgres_password backups || true
} > "$OUT/git-hygiene.txt" 2>&1
cat "$OUT/git-hygiene.txt"
step "Готово"
echo "Файлы доказательств: $OUT"
ls -1 "$OUT" "$OUT/track2"
+35
View File
@@ -0,0 +1,35 @@
#!/bin/sh
set -eu
cd "$(dirname "$0")/.."
NAME=mtusi-lab2-api-shortttl
PORT=${PORT:-8081}
NETWORK=$(docker compose --env-file .env ps --format '{{.Name}}' api | head -1 | xargs -I{} docker inspect {} --format '{{range $k,$v := .NetworkSettings.Networks}}{{$k}}{{end}}')
cleanup() {
docker rm -f "$NAME" >/dev/null 2>&1 || true
}
trap cleanup EXIT
cleanup
echo "Поднимаю отдельный API с SESSION_TTL_SECONDS=2 на порту $PORT (сеть $NETWORK)"
docker run -d --name "$NAME" --network "$NETWORK" \
-p 127.0.0.1:"$PORT":8080 \
-v "$PWD/secrets/database_url:/run/secrets/database_url:ro" \
-v "$PWD/secrets/cache_url:/run/secrets/cache_url:ro" \
-e DATABASE_URL_FILE=/run/secrets/database_url \
-e CACHE_URL_FILE=/run/secrets/cache_url \
-e SESSION_TTL_SECONDS=2 \
-e SESSION_CACHE_TTL_SECONDS=2 \
-e SESSION_SWEEP_SECONDS=5 \
mtusi-messenger:lab2 >/dev/null
i=0
while [ "$i" -lt 60 ]; do
if curl -fsS "http://localhost:$PORT/health/ready" >/dev/null 2>&1; then break; fi
i=$((i + 1))
sleep 1
done
curl -fsS "http://localhost:$PORT/health/ready" >/dev/null
python3 student-tests/test_expiry.py --base-url "http://localhost:$PORT"
+15
View File
@@ -0,0 +1,15 @@
#!/bin/sh
set -eu
cd "$(dirname "$0")/.."
TOTAL=${TOTAL:-10000}
PSQL="docker compose --env-file .env exec -T postgres psql -U messenger -d messenger -X -q"
echo "=== Стенд ==="
docker compose --env-file .env ps --format '{{.Service}} {{.Image}} {{.Status}}'
echo
echo "=== Засев $TOTAL сообщений с неравномерными чатами ==="
$PSQL -v total="$TOTAL" -f - < student-tests/seed.sql
echo
echo "=== План запроса истории ==="
$PSQL -f - < student-tests/explain.sql
+51
View File
@@ -0,0 +1,51 @@
\set ON_ERROR_STOP on
SELECT version() AS postgres_version;
SELECT count(*) AS messages_total,
count(DISTINCT chat_id) AS chats_with_messages,
pg_size_pretty(pg_table_size('messages')) AS table_size,
pg_size_pretty(pg_indexes_size('messages')) AS indexes_size
FROM messages;
\echo '--- распределение истории по чатам: 5 самых больших и 5 самых маленьких ---'
SELECT chat_id, count(*) AS rows FROM messages GROUP BY chat_id ORDER BY count(*) DESC LIMIT 5;
SELECT chat_id, count(*) AS rows FROM messages GROUP BY chat_id ORDER BY count(*) ASC LIMIT 5;
SELECT chat_id AS big_chat, count(*) AS big_rows
FROM messages GROUP BY chat_id ORDER BY count(*) DESC LIMIT 1 \gset
SELECT created_at AS cur_ts, id AS cur_id
FROM messages
WHERE chat_id = :'big_chat'
ORDER BY created_at, id
OFFSET (:'big_rows'::bigint * 9 / 10) LIMIT 1 \gset
\echo '--- A. keyset, первая страница самого большого чата ---'
EXPLAIN (ANALYZE, BUFFERS)
SELECT id, chat_id, sender_id, text, created_at
FROM messages
WHERE chat_id = :'big_chat'
ORDER BY created_at, id
LIMIT 50;
\echo '--- B. keyset, страница на глубине 90% истории (так работает cursor API) ---'
EXPLAIN (ANALYZE, BUFFERS)
SELECT id, chat_id, sender_id, text, created_at
FROM messages
WHERE chat_id = :'big_chat'
AND (created_at, id) > (:'cur_ts'::timestamptz, :'cur_id'::uuid)
ORDER BY created_at, id
LIMIT 50;
\echo '--- C. OFFSET на той же глубине (так API не делает: цена растёт со страницей) ---'
EXPLAIN (ANALYZE, BUFFERS)
SELECT id, chat_id, sender_id, text, created_at
FROM messages
WHERE chat_id = :'big_chat'
ORDER BY created_at, id
OFFSET (:'big_rows'::bigint * 9 / 10) LIMIT 50;
\echo '--- индексы таблицы messages ---'
SELECT indexrelname AS index, pg_size_pretty(pg_relation_size(indexrelid)) AS size, idx_scan AS scans
FROM pg_stat_user_indexes WHERE relname = 'messages' ORDER BY indexrelname;
+37
View File
@@ -0,0 +1,37 @@
\set ON_ERROR_STOP on
INSERT INTO users (id, username, display_name, password_hash, created_at)
SELECT gen_random_uuid(), 'load_' || g, convert_to('Нагрузка ' || g, 'UTF8'), 'seed-row-cannot-log-in', now()
FROM generate_series(1, 20) AS g
ON CONFLICT (username) DO NOTHING;
INSERT INTO chats (id, title, created_at)
SELECT gen_random_uuid(), convert_to('load chat ' || g, 'UTF8'), now()
FROM generate_series(1, 50) AS g
WHERE NOT EXISTS (SELECT 1 FROM chats WHERE title = convert_to('load chat ' || g, 'UTF8'));
INSERT INTO chat_members (chat_id, user_id)
SELECT c.id, u.id
FROM chats c CROSS JOIN users u
WHERE position(convert_to('load chat ', 'UTF8') in c.title) = 1 AND u.username LIKE 'load\_%'
ON CONFLICT DO NOTHING;
SELECT greatest(0, :total - (SELECT count(*) FROM messages)) AS to_seed \gset
SELECT clock_timestamp() AS seed_started \gset
WITH c AS (SELECT array_agg(id ORDER BY title) AS ids FROM chats WHERE position(convert_to('load chat ', 'UTF8') in title) = 1),
u AS (SELECT array_agg(id ORDER BY username) AS ids FROM users WHERE username LIKE 'load\_%')
INSERT INTO messages (id, chat_id, sender_id, text, created_at)
SELECT gen_random_uuid(),
c.ids[1 + floor(array_length(c.ids, 1) * power(random(), 3))::int],
u.ids[1 + floor(array_length(u.ids, 1) * random())::int],
convert_to('load message ' || g || ' ' || md5(g::text), 'UTF8'),
now() - make_interval(secs => (:to_seed - g) / 100.0)
FROM generate_series(1, :to_seed) AS g, c, u;
SELECT clock_timestamp() - :'seed_started'::timestamptz AS seed_duration,
:to_seed AS seeded_rows,
:total AS target_total,
(SELECT count(*) FROM messages) AS messages_total;
ANALYZE users, chats, chat_members, messages;
+114
View File
@@ -0,0 +1,114 @@
#!/usr/bin/env python3
"""Level 4: session semantics — wrong password, challenges, logout, token quality."""
import json
import uuid
from common import arguments, basic, call, credentials, expect, login, member, register, run
def wrong_password_gives_same_401(base):
actor = register(base, "pw")
name = actor["registration"]["username"]
wrong = call(base, "POST", "/api/v1/auth/sessions", headers={"Authorization": basic(name, "wrong-password-123")})
unknown = call(base, "POST", "/api/v1/auth/sessions", headers={"Authorization": basic("u_absent_" + uuid.uuid4().hex[:8], "wrong-password-123")})
expect(wrong["status"] == unknown["status"] == 401, "ожидался 401 в обоих случаях")
expect(wrong["json"]["error"]["code"] == unknown["json"]["error"]["code"] == "unauthorized", "код ошибки отличается")
expect(wrong["headers"].get("WWW-Authenticate", "").startswith("Basic"), "нет Basic challenge")
expect(wrong["json"]["error"]["request_id"] == wrong["headers"].get("X-Request-Id"), "request_id не совпадает с заголовком")
def basic_is_rejected_on_business_endpoints(base):
actor = register(base, "basic")
name = actor["registration"]["username"]
password = actor["registration"]["password"]
result = call(base, "GET", "/api/v1/users/me", headers={"Authorization": basic(name, password)})
expect(result["status"] == 401, "Basic на /users/me вернул %s" % result["status"])
expect(result["headers"].get("WWW-Authenticate", "").startswith("Bearer"), "нет Bearer challenge")
def x_user_id_does_not_authenticate(base):
alice = member(base, "alice")
bob = register(base, "bob")
anonymous = call(base, "GET", "/api/v1/users/me", headers={"X-User-Id": alice["id"]})
expect(anonymous["status"] == 401, "X-User-Id без Bearer дал %s" % anonymous["status"])
overridden = call(base, "GET", "/api/v1/users/me", token=alice["token"], headers={"X-User-Id": bob["id"]})
expect(overridden["status"] == 200 and overridden["json"]["id"] == alice["id"], "X-User-Id подменил владельца сессии")
def logout_revokes_only_its_own_token(base):
actor = member(base, "logout")
second = login(base, dict(actor))
first_token = actor["token"]
revoked = call(base, "DELETE", "/api/v1/auth/sessions/current", token=first_token)
expect(revoked["status"] == 204, "logout вернул %s" % revoked["status"])
expect(call(base, "GET", "/api/v1/users/me", token=first_token)["status"] == 401, "отозванный токен всё ещё работает")
expect(call(base, "DELETE", "/api/v1/auth/sessions/current", token=first_token)["status"] == 401, "повторный logout не 401")
expect(call(base, "GET", "/api/v1/users/me", token=second["token"])["status"] == 200, "logout убил вторую сессию")
def token_is_opaque_and_unique(base):
actor = member(base, "token")
name = actor["registration"]["username"]
expect(len(actor["token"]) >= 32, "токен короче 32 символов")
expect(name not in actor["token"] and actor["id"] not in actor["token"], "токен раскрывает имя или id пользователя")
again = login(base, dict(actor))
expect(again["token"] != actor["token"], "повторный вход выдал тот же токен")
expect(actor["session"]["token_type"] == "Bearer", "token_type не Bearer")
def short_password_is_rejected(base):
body = credentials("short")
body["password"] = "short"
expect(call(base, "POST", "/api/v1/users", body=body)["status"] == 400, "короткий пароль принят")
body = credentials("long")
body["password"] = "x" * 129
expect(call(base, "POST", "/api/v1/users", body=body)["status"] == 400, "пароль длиннее 128 принят")
def password_is_never_returned(base):
actor = member(base, "leak")
expect("password" not in actor["user"] and "password_hash" not in actor["user"], "User содержит пароль")
me = call(base, "GET", "/api/v1/users/me", token=actor["token"])["json"]
expect(set(me) == {"id", "username", "display_name", "created_at"}, "в /users/me лишние поля: %s" % sorted(me))
expect("password" not in str(actor["session"]["user"]), "сессия раскрывает пароль")
def login_rejects_a_request_body(base):
actor = register(base, "body")
header = basic(actor["registration"]["username"], actor["registration"]["password"])
with_body = call(base, "POST", "/api/v1/auth/sessions", body={"username": actor["registration"]["username"]}, headers={"Authorization": header})
expect(with_body["status"] == 400, "вход с JSON-телом дал %s" % with_body["status"])
raw_body = call(base, "POST", "/api/v1/auth/sessions", raw=b"anything", headers={"Authorization": header}, content_type="text/plain")
expect(raw_body["status"] == 400, "вход с произвольным телом дал %s" % raw_body["status"])
clean = call(base, "POST", "/api/v1/auth/sessions", headers={"Authorization": header})
expect(clean["status"] == 201, "вход без тела дал %s" % clean["status"])
def broken_utf8_credentials_are_rejected(base):
actor = register(base, "utf8")
name = actor["registration"]["username"]
import base64 as b64
header = "Basic " + b64.b64encode(name.encode() + b":" + actor["registration"]["password"].encode() + b"\xff").decode()
result = call(base, "POST", "/api/v1/auth/sessions", headers={"Authorization": header})
expect(result["status"] == 401, "повреждённый UTF-8 в пароле дал %s" % result["status"])
body = credentials("utf8reg")
bad_body = json.dumps(body, ensure_ascii=False).encode("utf-8").replace(b'"password"', b'"passw\xffrd"')
broken = call(base, "POST", "/api/v1/users", raw=bad_body, content_type="application/json")
expect(broken["status"] == 400, "повреждённый UTF-8 в теле дал %s" % broken["status"])
TESTS = [
wrong_password_gives_same_401,
basic_is_rejected_on_business_endpoints,
x_user_id_does_not_authenticate,
logout_revokes_only_its_own_token,
token_is_opaque_and_unique,
short_password_is_rejected,
password_is_never_returned,
login_rejects_a_request_body,
broken_utf8_credentials_are_rejected,
]
if __name__ == "__main__":
run(TESTS, arguments(__doc__).base_url)
+44
View File
@@ -0,0 +1,44 @@
#!/usr/bin/env python3
"""Level 4: session expiry on a short SESSION_TTL_SECONDS instance."""
import time
from common import arguments, call, expect, member, run
TTL = 2
def session_expires_after_ttl(base):
actor = member(base, "ttl")
alive = call(base, "GET", "/api/v1/users/me", token=actor["token"])
expect(alive["status"] == 200, "свежая сессия дала %s" % alive["status"])
time.sleep(TTL + 2)
expired = call(base, "GET", "/api/v1/users/me", token=actor["token"])
expect(expired["status"] == 401, "истёкшая сессия дала %s" % expired["status"])
expect(expired["headers"].get("WWW-Authenticate", "").startswith("Bearer"), "нет Bearer challenge")
expect(expired["json"]["error"]["code"] == "unauthorized", "код ошибки %s" % expired["json"]["error"]["code"])
def expired_session_cannot_write_or_logout(base):
alice = member(base, "ttlwrite")
bob = member(base, "ttlwrite2")
chat = call(base, "POST", "/api/v1/chats", body={"title": "Срок жизни", "member_ids": [alice["id"], bob["id"]]}, token=alice["token"])
expect(chat["status"] == 201, "создание чата дало %s" % chat["status"])
time.sleep(TTL + 2)
write = call(base, "POST", "/api/v1/chats/%s/messages" % chat["json"]["id"], body={"text": "после истечения"}, token=alice["token"])
expect(write["status"] == 401, "запись истёкшим токеном дала %s" % write["status"])
expect(call(base, "DELETE", "/api/v1/auth/sessions/current", token=alice["token"])["status"] == 401, "logout истёкшим токеном не 401")
def expires_at_matches_configured_ttl(base):
import datetime as dt
actor = member(base, "ttlvalue")
expires_at = dt.datetime.fromisoformat(actor["session"]["expires_at"][:-1] + "+00:00")
remaining = (expires_at - dt.datetime.now(dt.timezone.utc)).total_seconds()
expect(0 < remaining <= TTL + 1, "expires_at обещает %.1f c при TTL=%d" % (remaining, TTL))
TESTS = [session_expires_after_ttl, expired_session_cannot_write_or_logout, expires_at_matches_configured_ttl]
if __name__ == "__main__":
run(TESTS, arguments(__doc__).base_url)
+93
View File
@@ -0,0 +1,93 @@
#!/usr/bin/env python3
"""Level 4/5: revocation must outlive the cache and outages must never grant trust."""
import pathlib
import subprocess
import time
from common import arguments, call, chat_with, expect, member, run
ROOT = pathlib.Path(__file__).resolve().parents[1]
COMPOSE = ["docker", "compose", "--env-file", ".env"]
def compose(*args):
subprocess.run(COMPOSE + list(args), cwd=str(ROOT), check=True, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
def wait_ready(base, seconds=90):
deadline = time.monotonic() + seconds
while time.monotonic() < deadline:
try:
if call(base, "GET", "/health/ready")["status"] == 200:
return
except AssertionError:
pass
time.sleep(0.5)
raise AssertionError("API не стал ready за %d с" % seconds)
def revoked_session_stays_revoked_after_cache_restart(base):
actor = member(base, "revoke")
expect(call(base, "GET", "/api/v1/users/me", token=actor["token"])["status"] == 200, "свежая сессия не работает")
expect(call(base, "DELETE", "/api/v1/auth/sessions/current", token=actor["token"])["status"] == 204, "logout не вернул 204")
compose("restart", "valkey")
wait_ready(base)
after = call(base, "GET", "/api/v1/users/me", token=actor["token"])
expect(after["status"] == 401, "отозванная сессия вернула доступ после рестарта кэша: %s" % after["status"])
def logout_is_not_confirmed_while_cache_is_down(base):
actor = member(base, "logoutdown")
expect(call(base, "GET", "/api/v1/users/me", token=actor["token"])["status"] == 200, "свежая сессия не работает")
compose("stop", "valkey")
try:
refused = call(base, "DELETE", "/api/v1/auth/sessions/current", token=actor["token"])
expect(refused["status"] == 503, "logout без кэша дал %s вместо 503" % refused["status"])
still = call(base, "GET", "/api/v1/users/me", token=actor["token"])
expect(still["status"] == 200, "сессия не отозвана, но доступ уже потерян: %s" % still["status"])
finally:
compose("start", "valkey")
wait_ready(base)
expect(call(base, "DELETE", "/api/v1/auth/sessions/current", token=actor["token"])["status"] == 204, "повторный logout не прошёл")
expect(call(base, "GET", "/api/v1/users/me", token=actor["token"])["status"] == 401, "после подтверждённого logout токен жив")
def cached_sessions_do_not_cross_users(base):
alice = member(base, "cross")
bob = member(base, "cross2")
for _ in range(3):
first = call(base, "GET", "/api/v1/users/me", token=alice["token"])["json"]
second = call(base, "GET", "/api/v1/users/me", token=bob["token"])["json"]
expect(first["id"] == alice["id"] and second["id"] == bob["id"], "кэш перепутал владельцев сессий")
chat = chat_with(base, alice, bob)
sent = call(base, "POST", "/api/v1/chats/%s/messages" % chat["id"], body={"text": "от боба"}, token=bob["token"])
expect(sent["json"]["sender_id"] == bob["id"], "sender_id взят не из сессии")
def hung_database_fails_fast(base):
actor = member(base, "hang")
compose("pause", "postgres")
try:
started = time.monotonic()
result = call(base, "GET", "/api/v1/chats", token=actor["token"], timeout=60)
elapsed = time.monotonic() - started
expect(result["status"] == 503, "зависшая БД дала %s вместо 503" % result["status"])
expect(elapsed < 10, "ответ пришёл за %.1f с при заявленном клиентском лимите 6 с" % elapsed)
ready = call(base, "GET", "/health/ready", timeout=60)
expect(ready["status"] == 503, "/health/ready при зависшей БД дал %s" % ready["status"])
expect(call(base, "GET", "/health/live", timeout=60)["status"] == 200, "/health/live упал вместе с БД")
finally:
compose("unpause", "postgres")
wait_ready(base)
expect(call(base, "GET", "/api/v1/chats", token=actor["token"])["status"] == 200, "после возврата БД доступ не восстановился")
TESTS = [
revoked_session_stays_revoked_after_cache_restart,
logout_is_not_confirmed_while_cache_is_down,
cached_sessions_do_not_cross_users,
hung_database_fails_fast,
]
if __name__ == "__main__":
run(TESTS, arguments(__doc__).base_url)
+242
View File
@@ -0,0 +1,242 @@
#!/usr/bin/env python3
"""Level 4: PostgreSQL rules — username race, transaction rollback, keyset paging, injection."""
import threading
import uuid
from urllib.parse import quote
from common import arguments, call, chat_with, credentials, expect, member, run
RACE_CLIENTS = 12
def duplicate_username_race_creates_one_user(base):
body = credentials("race")
results = []
lock = threading.Lock()
ready = threading.Barrier(RACE_CLIENTS)
def attempt():
ready.wait()
result = call(base, "POST", "/api/v1/users", body=body)
with lock:
results.append(result["status"])
threads = [threading.Thread(target=attempt) for _ in range(RACE_CLIENTS)]
for thread in threads:
thread.start()
for thread in threads:
thread.join()
created = results.count(201)
conflicts = results.count(409)
expect(created == 1, "создано %d пользователей с одним username (ожидался 1): %s" % (created, results))
expect(created + conflicts == RACE_CLIENTS, "неожиданные ответы в гонке: %s" % results)
def unknown_member_rolls_chat_back(base):
alice = member(base, "rollback")
title = "Откат " + uuid.uuid4().hex[:8]
body = {"title": title, "member_ids": [alice["id"], str(uuid.uuid4())]}
result = call(base, "POST", "/api/v1/chats", body=body, token=alice["token"])
expect(result["status"] == 400, "неизвестный участник дал %s" % result["status"])
listed = call(base, "GET", "/api/v1/chats?limit=100", token=alice["token"])["json"]
expect(all(chat["title"] != title for chat in listed["items"]), "чат остался в базе после отката")
def keyset_pagination_is_complete(base):
alice = member(base, "pages")
bob = member(base, "pages2")
chat = chat_with(base, alice, bob)
total = 25
for index in range(total):
result = call(base, "POST", "/api/v1/chats/%s/messages" % chat["id"], body={"text": "сообщение %d" % index}, token=alice["token"])
expect(result["status"] == 201, "отправка %d вернула %s" % (index, result["status"]))
seen = []
cursor = None
for _ in range(total):
path = "/api/v1/chats/%s/messages?limit=7" % chat["id"]
if cursor:
path += "&cursor=" + quote(cursor, safe="")
page = call(base, "GET", path, token=bob["token"])["json"]
seen.extend(page["items"])
cursor = page["next_cursor"]
if cursor is None:
break
expect(cursor is None, "обход истории не завершился")
ids = [item["id"] for item in seen]
expect(len(ids) == total, "прочитано %d сообщений из %d" % (len(ids), total))
expect(len(set(ids)) == total, "в обходе есть повторы")
keys = [(item["created_at"], uuid.UUID(item["id"]).int) for item in seen]
expect(keys == sorted(keys), "порядок (created_at, id) нарушен")
def cursor_is_bound_to_its_chat(base):
alice = member(base, "cursor")
bob = member(base, "cursor2")
first = chat_with(base, alice, bob)
second = chat_with(base, alice, bob)
for chat in (first, second):
for index in range(3):
call(base, "POST", "/api/v1/chats/%s/messages" % chat["id"], body={"text": "текст %d" % index}, token=alice["token"])
page = call(base, "GET", "/api/v1/chats/%s/messages?limit=1" % first["id"], token=alice["token"])["json"]
expect(page["next_cursor"], "нет курсора для проверки")
foreign = call(base, "GET", "/api/v1/chats/%s/messages?limit=1&cursor=%s" % (second["id"], quote(page["next_cursor"], safe="")), token=alice["token"])
expect(foreign["status"] == 400, "курсор другого чата принят: %s" % foreign["status"])
tampered = page["next_cursor"][:-2] + ("aa" if not page["next_cursor"].endswith("aa") else "bb")
altered = call(base, "GET", "/api/v1/chats/%s/messages?cursor=%s" % (first["id"], quote(tampered, safe="")), token=alice["token"])
expect(altered["status"] == 400, "изменённый курсор принят: %s" % altered["status"])
def limit_bounds_are_enforced(base):
alice = member(base, "limit")
bob = member(base, "limit2")
chat = chat_with(base, alice, bob)
for value in ("0", "101", "abc", "-1", "1.5", ""):
result = call(base, "GET", "/api/v1/chats/%s/messages?limit=%s" % (chat["id"], quote(value, safe="")), token=alice["token"])
expect(result["status"] == 400, "limit=%r дал %s" % (value, result["status"]))
valid = call(base, "GET", "/api/v1/chats/%s/messages?limit=100" % chat["id"], token=alice["token"])
expect(valid["status"] == 200, "limit=100 дал %s" % valid["status"])
def sql_injection_is_not_executed(base):
probes = ["ad'; DROP TABLE users; --", "' OR '1'='1", "admin\"--", "ad\\'; SELECT 1"]
for probe in probes:
body = credentials("inj")
body["username"] = probe
result = call(base, "POST", "/api/v1/users", body=body)
expect(result["status"] == 400, "username %r дал %s" % (probe, result["status"]))
alice = member(base, "after")
bob = member(base, "after2")
chat = chat_with(base, alice, bob)
text = "текст с кавычкой ' и ; DROP TABLE messages; --"
created = call(base, "POST", "/api/v1/chats/%s/messages" % chat["id"], body={"text": text}, token=alice["token"])
expect(created["status"] == 201 and created["json"]["text"] == text, "текст с кавычками испорчен или отклонён")
history = call(base, "GET", "/api/v1/chats/%s/messages" % chat["id"], token=bob["token"])["json"]
expect(any(item["text"] == text for item in history["items"]), "сообщение не читается после вставки")
def malformed_requests_are_rejected(base):
alice = member(base, "shape")
bob = member(base, "shape2")
chat = chat_with(base, alice, bob)
path = "/api/v1/chats/%s/messages" % chat["id"]
expect(call(base, "POST", path, body={"text": "ок", "sender_id": alice["id"]}, token=alice["token"])["status"] == 400, "лишнее поле принято")
expect(call(base, "POST", path, body={}, token=alice["token"])["status"] == 400, "пустой объект принят")
expect(call(base, "POST", path, body={"text": " "}, token=alice["token"])["status"] == 400, "пробельный текст принят")
expect(call(base, "POST", path, body={"text": "x" * 4001}, token=alice["token"])["status"] == 400, "текст длиннее 4000 принят")
expect(call(base, "GET", "/api/v1/chats/not-a-uuid", token=alice["token"])["status"] == 400, "неверный UUID дал не 400")
expect(call(base, "GET", "/api/v1/chats/%s" % uuid.uuid4(), token=alice["token"])["status"] == 404, "чужой чат дал не 404")
def nul_and_unicode_text_round_trips(base):
alice = member(base, "unicode")
bob = member(base, "unicode2")
chat = chat_with(base, alice, bob)
path = "/api/v1/chats/%s/messages" % chat["id"]
samples = [
"a\u0000b",
"\u0000",
"emoji \U0001f44b и ZWJ \U0001f469\u200d\U0001f4bb",
"комбинация e\u0301 и RTL \u05d0\u05d1",
"край \u0007\u001b\u007f",
]
created = []
for sample in samples:
result = call(base, "POST", path, body={"text": sample}, token=alice["token"])
expect(result["status"] == 201, "текст %r дал %s" % (sample, result["status"]))
expect(result["json"]["text"] == sample, "текст изменён при записи: %r -> %r" % (sample, result["json"]["text"]))
created.append(result["json"])
history = call(base, "GET", path + "?limit=100", token=bob["token"])["json"]["items"]
by_id = {item["id"]: item["text"] for item in history}
for item in created:
expect(by_id.get(item["id"]) == item["text"], "текст изменён при чтении: %r" % item["text"])
def text_length_limit_counts_code_points(base):
alice = member(base, "length")
bob = member(base, "length2")
chat = chat_with(base, alice, bob)
path = "/api/v1/chats/%s/messages" % chat["id"]
exact = "\U0001f600" * 4000
result = call(base, "POST", path, body={"text": exact}, token=alice["token"])
expect(result["status"] == 201, "4000 code points дали %s" % result["status"])
expect(result["json"]["text"] == exact, "текст на границе изменён")
over = call(base, "POST", path, body={"text": "\U0001f600" * 4001}, token=alice["token"])
expect(over["status"] == 400, "4001 code point дал %s" % over["status"])
def unicode_blanks_are_rejected(base):
alice = member(base, "blank")
bob = member(base, "blank2")
chat = chat_with(base, alice, bob)
path = "/api/v1/chats/%s/messages" % chat["id"]
blanks = [" ", "\t\n", "\u00a0", "\u2007", "\u3000", "\u200b", "\u200b \u200b", "\ufeff"]
for blank in blanks:
result = call(base, "POST", path, body={"text": blank}, token=alice["token"])
expect(result["status"] == 400, "пробельный текст %r дал %s" % (blank, result["status"]))
for field in ("display_name",):
body = credentials("blank")
body[field] = "\u200b"
expect(call(base, "POST", "/api/v1/users", body=body)["status"] == 400, "пустой %s принят" % field)
titles = call(base, "POST", "/api/v1/chats", body={"title": "\u00a0", "member_ids": [alice["id"]]}, token=alice["token"])
expect(titles["status"] == 400, "пробельный title принят: %s" % titles["status"])
def broken_json_does_not_break_the_api(base):
alice = member(base, "json")
bob = member(base, "json2")
chat = chat_with(base, alice, bob)
path = "/api/v1/chats/%s/messages" % chat["id"]
payloads = [
b'{"text": 1e999}',
b'{"text": NaN}',
b'{"text": Infinity}',
b'{"text": 1e+}',
b'{"text": ' + b"9" * 5000 + b"}",
b'{"text": ' + b"[" * 2000 + b"]" * 2000 + b"}",
b"[" * 2000,
b'{"text": {"text": "nested object"}}',
b'{"text": "\xff\xfe"}',
b"",
b"{",
]
for payload in payloads:
result = call(base, "POST", path, raw=payload, token=alice["token"], content_type="application/json")
expect(result["status"] == 400, "тело %r дало %s" % (payload[:24], result["status"]))
alive = call(base, "POST", path, body={"text": "после битого JSON"}, token=alice["token"])
expect(alive["status"] == 201, "API не отвечает после битых тел: %s" % alive["status"])
def content_type_is_required(base):
alice = member(base, "ctype")
bob = member(base, "ctype2")
chat = chat_with(base, alice, bob)
path = "/api/v1/chats/%s/messages" % chat["id"]
for content_type in ("text/plain", "application/x-www-form-urlencoded", "", "application/jsonx"):
result = call(base, "POST", path, raw=b'{"text":"x"}', token=alice["token"], content_type=content_type)
expect(result["status"] == 415, "Content-Type %r дал %s" % (content_type, result["status"]))
body = credentials("ctype")
import json as jsonlib
plain = call(base, "POST", "/api/v1/users", raw=jsonlib.dumps(body).encode(), content_type="text/plain")
expect(plain["status"] == 415, "регистрация с text/plain дала %s" % plain["status"])
charset = call(base, "POST", path, raw=b'{"text":"charset"}', token=alice["token"], content_type="application/json; charset=utf-8")
expect(charset["status"] == 201, "application/json с charset дал %s" % charset["status"])
TESTS = [
duplicate_username_race_creates_one_user,
unknown_member_rolls_chat_back,
keyset_pagination_is_complete,
cursor_is_bound_to_its_chat,
limit_bounds_are_enforced,
sql_injection_is_not_executed,
malformed_requests_are_rejected,
nul_and_unicode_text_round_trips,
text_length_limit_counts_code_points,
unicode_blanks_are_rejected,
broken_json_does_not_break_the_api,
content_type_is_required,
]
if __name__ == "__main__":
run(TESTS, arguments(__doc__).base_url)
+32
View File
@@ -0,0 +1,32 @@
#!/usr/bin/env python3
"""Level 4: the API keeps working from PostgreSQL while the session cache is down."""
from common import arguments, call, chat_with, expect, member, run
def login_and_read_work_without_cache(base):
alice = member(base, "nocache")
bob = member(base, "nocache2")
me = call(base, "GET", "/api/v1/users/me", token=alice["token"])
expect(me["status"] == 200 and me["json"]["id"] == alice["id"], "/users/me без кэша дал %s" % me["status"])
chat = chat_with(base, alice, bob)
sent = call(base, "POST", "/api/v1/chats/%s/messages" % chat["id"], body={"text": "кэш выключен"}, token=alice["token"])
expect(sent["status"] == 201, "запись без кэша дала %s" % sent["status"])
history = call(base, "GET", "/api/v1/chats/%s/messages" % chat["id"], token=bob["token"])
expect(history["status"] == 200, "чтение без кэша дало %s" % history["status"])
expect(any(item["id"] == sent["json"]["id"] for item in history["json"]["items"]), "сообщение не видно без кэша")
def unknown_token_is_still_rejected(base):
expect(call(base, "GET", "/api/v1/users/me", token="definitely-not-a-valid-session-token")["status"] == 401, "неизвестный токен принят")
expect(call(base, "GET", "/api/v1/users/me")["status"] == 401, "анонимный запрос принят")
def readiness_ignores_the_cache(base):
ready = call(base, "GET", "/health/ready")
expect(ready["status"] == 200, "/health/ready без кэша дал %s" % ready["status"])
TESTS = [login_and_read_work_without_cache, unknown_token_is_still_rejected, readiness_ignores_the_cache]
if __name__ == "__main__":
run(TESTS, arguments(__doc__).base_url)
+41
View File
@@ -0,0 +1,41 @@
#!/usr/bin/env python3
"""Level 4: with PostgreSQL stopped the API degrades to a bounded error, never to trust."""
import uuid
from common import arguments, call, expect, run
def readiness_reports_the_outage(base):
ready = call(base, "GET", "/health/ready")
expect(ready["status"] == 503, "/health/ready без БД дал %s" % ready["status"])
expect(ready["json"]["error"]["code"] == "unavailable", "код ошибки %s" % ready["json"]["error"]["code"])
live = call(base, "GET", "/health/live")
expect(live["status"] == 200, "/health/live без БД дал %s" % live["status"])
def writes_fail_with_503(base):
body = {"username": "u_nodb_" + uuid.uuid4().hex[:8], "display_name": "Без БД", "password": "T3st-" + uuid.uuid4().hex}
created = call(base, "POST", "/api/v1/users", body=body)
expect(created["status"] == 503, "регистрация без БД дала %s" % created["status"])
def unknown_token_never_becomes_trusted(base):
for token in ("definitely-not-a-valid-session-token", uuid.uuid4().hex):
result = call(base, "GET", "/api/v1/users/me", token=token)
expect(result["status"] in (401, 503), "неизвестный токен без БД дал %s" % result["status"])
anonymous = call(base, "GET", "/api/v1/chats", token=None)
expect(anonymous["status"] == 401, "анонимный запрос без БД дал %s" % anonymous["status"])
def login_fails_closed(base):
import base64
header = "Basic " + base64.b64encode(b"u_any_user:any-password-123").decode()
result = call(base, "POST", "/api/v1/auth/sessions", headers={"Authorization": header})
expect(result["status"] in (401, 503), "вход без БД дал %s" % result["status"])
TESTS = [readiness_reports_the_outage, writes_fail_with_503, unknown_token_never_becomes_trusted, login_fails_closed]
if __name__ == "__main__":
run(TESTS, arguments(__doc__).base_url)
+113
View File
@@ -0,0 +1,113 @@
#!/bin/sh
set -eu
cd "$(dirname "$0")/.."
TOTAL=${TOTAL:-120000}
IMAGE=postgres:17.7-alpine@sha256:bb377b7239d2774ac8cc76f481596ce96c5a6b5e9d141f6d0a0ee371a6e7c0f2
RNAME=mtusi-lab2-restore
RVOL=mtusi-lab2-restore-data
PSQL="docker compose --env-file .env exec -T postgres psql -U messenger -d messenger -X -q"
RPSQL="docker exec -i $RNAME psql -U messenger -d messenger_restored -X -q"
STAMP=$(date +%Y%m%d-%H%M%S)
DUMP="backups/messenger-$STAMP.dump"
now_ms() {
python3 -c 'import time; print(int(time.time() * 1000))'
}
elapsed() {
python3 -c "print('%.3f' % ((int('$2') - int('$1')) / 1000.0))"
}
cleanup() {
if [ "${KEEP:-0}" != "1" ]; then
docker rm -f "$RNAME" >/dev/null 2>&1 || true
docker volume rm "$RVOL" >/dev/null 2>&1 || true
fi
}
trap cleanup EXIT
mkdir -p backups
echo "=== Стенд и версии ==="
docker compose --env-file .env ps --format '{{.Service}} {{.Image}} {{.Status}}'
uname -sm
docker --version
echo
echo "=== 1. Засев истории: цель $TOTAL сообщений, чаты неравномерные ==="
$PSQL -v total="$TOTAL" -f - < student-tests/seed.sql
echo
echo "=== 2. Сравнение индексов и цены записи (каждый вариант в откатываемой транзакции) ==="
$PSQL -f - < student-tests/track2_indexes.sql
BIG_CHAT=$($PSQL -t -A -c "SELECT chat_id FROM messages GROUP BY chat_id ORDER BY count(*) DESC LIMIT 1")
echo
echo "Самый большой чат: $BIG_CHAT"
echo
echo "=== 3. Состояние источника до бэкапа ==="
$PSQL -v big_chat="$BIG_CHAT" -f - < student-tests/track2_verify.sql
echo
echo "=== 4. Бэкап pg_dump -Fc ==="
BACKUP_START=$(now_ms)
docker compose --env-file .env exec -T postgres pg_dump -U messenger -d messenger -Fc > "$DUMP"
BACKUP_END=$(now_ms)
echo "backup_seconds=$(elapsed "$BACKUP_START" "$BACKUP_END")"
echo "dump_size=$(du -h "$DUMP" | cut -f1)"
echo
echo "=== 5. Запись после бэкапа: граница потери данных ==="
$PSQL -c "INSERT INTO messages (id, chat_id, sender_id, text, created_at) SELECT gen_random_uuid(), '$BIG_CHAT', sender_id, convert_to('marker after backup $STAMP', 'UTF8'), clock_timestamp() FROM messages WHERE chat_id = '$BIG_CHAT' LIMIT 1"
$PSQL -t -A -c "SELECT 'в источнике маркеров: ' || count(*) FROM messages WHERE position(convert_to('marker after backup', 'UTF8') in text) = 1"
echo
echo "=== 6. Новое хранилище: отдельный контейнер и отдельный том ==="
docker volume create "$RVOL" >/dev/null
docker run -d --name "$RNAME" \
-e POSTGRES_USER=messenger \
-e POSTGRES_DB=messenger_restored \
-e POSTGRES_PASSWORD_FILE=/run/secrets/postgres_password \
-v "$PWD/secrets/postgres_password:/run/secrets/postgres_password:ro" \
-v "$RVOL:/var/lib/postgresql/data" \
"$IMAGE" >/dev/null
i=0
while [ "$i" -lt 60 ]; do
if docker exec "$RNAME" pg_isready -U messenger -d messenger_restored >/dev/null 2>&1; then break; fi
i=$((i + 1))
sleep 1
done
docker exec "$RNAME" pg_isready -U messenger -d messenger_restored
echo
echo "=== 7. Восстановление в новое хранилище ==="
docker cp "$DUMP" "$RNAME:/tmp/restore.dump" >/dev/null
RESTORE_START=$(now_ms)
docker exec "$RNAME" pg_restore -U messenger -d messenger_restored --no-owner --exit-on-error /tmp/restore.dump
RESTORE_END=$(now_ms)
echo "restore_seconds=$(elapsed "$RESTORE_START" "$RESTORE_END")"
echo
echo "=== 8. Сверка восстановленной копии ==="
$RPSQL -v big_chat="$BIG_CHAT" -f - < student-tests/track2_verify.sql
echo
echo "=== 9. Итог ==="
SRC_MD5=$($PSQL -t -A -c "SELECT md5(string_agg(id::text || '|' || created_at::text || '|' || encode(text, 'hex'), E'\n' ORDER BY created_at, id)) FROM messages WHERE chat_id = '$BIG_CHAT' AND position(convert_to('marker after backup', 'UTF8') in text) <> 1")
DST_MD5=$($RPSQL -t -A -c "SELECT md5(string_agg(id::text || '|' || created_at::text || '|' || encode(text, 'hex'), E'\n' ORDER BY created_at, id)) FROM messages WHERE chat_id = '$BIG_CHAT'")
SRC_ROWS=$($PSQL -t -A -c "SELECT count(*) FROM messages WHERE position(convert_to('marker after backup', 'UTF8') in text) <> 1")
DST_ROWS=$($RPSQL -t -A -c "SELECT count(*) FROM messages")
echo "backup_seconds=$(elapsed "$BACKUP_START" "$BACKUP_END") restore_seconds=$(elapsed "$RESTORE_START" "$RESTORE_END")"
echo "messages_source_without_marker=$SRC_ROWS messages_restored=$DST_ROWS"
echo "big_chat_md5_source=$SRC_MD5"
echo "big_chat_md5_restored=$DST_MD5"
if [ "$SRC_MD5" = "$DST_MD5" ] && [ "$SRC_ROWS" = "$DST_ROWS" ]; then
echo "RESULT: восстановленная копия совпадает с источником на момент бэкапа"
else
echo "RESULT: расхождение, смотри таблицы выше"
exit 1
fi
MARKERS=$($RPSQL -t -A -c "SELECT count(*) FROM messages WHERE position(convert_to('marker after backup', 'UTF8') in text) = 1")
echo "маркеров после бэкапа в восстановленной копии: $MARKERS (ожидается 0: всё, что подтверждено после снимка, в дампе отсутствует)"
+104
View File
@@ -0,0 +1,104 @@
\set ON_ERROR_STOP on
SELECT count(*) AS messages_total FROM messages;
SELECT chat_id AS big_chat, count(*) AS big_rows
FROM messages GROUP BY chat_id ORDER BY count(*) DESC LIMIT 1 \gset
SELECT created_at AS cur_ts, id AS cur_id
FROM messages WHERE chat_id = :'big_chat'
ORDER BY created_at, id OFFSET (:'big_rows'::bigint * 9 / 10) LIMIT 1 \gset
\echo '############ Вариант A: messages_history_idx (chat_id, created_at, id) ############'
BEGIN;
ANALYZE messages;
SELECT pg_size_pretty(pg_relation_size('messages_history_idx')) AS index_size;
EXPLAIN (ANALYZE, BUFFERS)
SELECT id, chat_id, sender_id, text, created_at FROM messages
WHERE chat_id = :'big_chat' AND (created_at, id) > (:'cur_ts'::timestamptz, :'cur_id'::uuid)
ORDER BY created_at, id LIMIT 50;
SELECT clock_timestamp() AS q0 \gset
SELECT count(*) AS pages_measured FROM generate_series(1, 100) AS g,
LATERAL (
SELECT id FROM messages
WHERE chat_id = :'big_chat'
AND (created_at, id) > (:'cur_ts'::timestamptz + make_interval(secs => g * 0.001), :'cur_id'::uuid)
ORDER BY created_at, id LIMIT 50
) AS page;
SELECT clock_timestamp() - :'q0'::timestamptz AS hundred_pages_duration;
SELECT clock_timestamp() AS t0 \gset
WITH c AS (SELECT array_agg(id ORDER BY title) AS ids FROM chats WHERE position(convert_to('load chat ', 'UTF8') in title) = 1),
u AS (SELECT array_agg(id ORDER BY username) AS ids FROM users WHERE username LIKE 'load\_%')
INSERT INTO messages (id, chat_id, sender_id, text, created_at)
SELECT gen_random_uuid(),
c.ids[1 + floor(array_length(c.ids, 1) * power(random(), 3))::int],
u.ids[1 + floor(array_length(u.ids, 1) * random())::int],
convert_to('write cost A ' || g, 'UTF8'), now()
FROM generate_series(1, 10000) AS g, c, u;
SELECT clock_timestamp() - :'t0'::timestamptz AS insert_10k_duration;
ROLLBACK;
\echo '############ Вариант B: только (chat_id) ############'
BEGIN;
DROP INDEX messages_history_idx;
CREATE INDEX messages_chat_only_idx ON messages (chat_id);
ANALYZE messages;
SELECT pg_size_pretty(pg_relation_size('messages_chat_only_idx')) AS index_size;
EXPLAIN (ANALYZE, BUFFERS)
SELECT id, chat_id, sender_id, text, created_at FROM messages
WHERE chat_id = :'big_chat' AND (created_at, id) > (:'cur_ts'::timestamptz, :'cur_id'::uuid)
ORDER BY created_at, id LIMIT 50;
SELECT clock_timestamp() AS q0 \gset
SELECT count(*) AS pages_measured FROM generate_series(1, 100) AS g,
LATERAL (
SELECT id FROM messages
WHERE chat_id = :'big_chat'
AND (created_at, id) > (:'cur_ts'::timestamptz + make_interval(secs => g * 0.001), :'cur_id'::uuid)
ORDER BY created_at, id LIMIT 50
) AS page;
SELECT clock_timestamp() - :'q0'::timestamptz AS hundred_pages_duration;
SELECT clock_timestamp() AS t0 \gset
WITH c AS (SELECT array_agg(id ORDER BY title) AS ids FROM chats WHERE position(convert_to('load chat ', 'UTF8') in title) = 1),
u AS (SELECT array_agg(id ORDER BY username) AS ids FROM users WHERE username LIKE 'load\_%')
INSERT INTO messages (id, chat_id, sender_id, text, created_at)
SELECT gen_random_uuid(),
c.ids[1 + floor(array_length(c.ids, 1) * power(random(), 3))::int],
u.ids[1 + floor(array_length(u.ids, 1) * random())::int],
convert_to('write cost B ' || g, 'UTF8'), now()
FROM generate_series(1, 10000) AS g, c, u;
SELECT clock_timestamp() - :'t0'::timestamptz AS insert_10k_duration;
ROLLBACK;
\echo '############ Вариант C: (chat_id, created_at, id) INCLUDE (sender_id, text) ############'
BEGIN;
DROP INDEX messages_history_idx;
CREATE INDEX messages_history_covering_idx ON messages (chat_id, created_at, id) INCLUDE (sender_id, text);
ANALYZE messages;
SELECT pg_size_pretty(pg_relation_size('messages_history_covering_idx')) AS index_size;
EXPLAIN (ANALYZE, BUFFERS)
SELECT id, chat_id, sender_id, text, created_at FROM messages
WHERE chat_id = :'big_chat' AND (created_at, id) > (:'cur_ts'::timestamptz, :'cur_id'::uuid)
ORDER BY created_at, id LIMIT 50;
SELECT clock_timestamp() AS q0 \gset
SELECT count(*) AS pages_measured FROM generate_series(1, 100) AS g,
LATERAL (
SELECT id FROM messages
WHERE chat_id = :'big_chat'
AND (created_at, id) > (:'cur_ts'::timestamptz + make_interval(secs => g * 0.001), :'cur_id'::uuid)
ORDER BY created_at, id LIMIT 50
) AS page;
SELECT clock_timestamp() - :'q0'::timestamptz AS hundred_pages_duration;
SELECT clock_timestamp() AS t0 \gset
WITH c AS (SELECT array_agg(id ORDER BY title) AS ids FROM chats WHERE position(convert_to('load chat ', 'UTF8') in title) = 1),
u AS (SELECT array_agg(id ORDER BY username) AS ids FROM users WHERE username LIKE 'load\_%')
INSERT INTO messages (id, chat_id, sender_id, text, created_at)
SELECT gen_random_uuid(),
c.ids[1 + floor(array_length(c.ids, 1) * power(random(), 3))::int],
u.ids[1 + floor(array_length(u.ids, 1) * random())::int],
convert_to('write cost C ' || g, 'UTF8'), now()
FROM generate_series(1, 10000) AS g, c, u;
SELECT clock_timestamp() - :'t0'::timestamptz AS insert_10k_duration;
ROLLBACK;
\echo '############ Схема после эксперимента (ROLLBACK вернул индексы) ############'
SELECT indexname FROM pg_indexes WHERE tablename = 'messages' ORDER BY indexname;
+17
View File
@@ -0,0 +1,17 @@
\set ON_ERROR_STOP on
SELECT 'users' AS relation, count(*) AS rows FROM users
UNION ALL SELECT 'chats', count(*) FROM chats
UNION ALL SELECT 'chat_members', count(*) FROM chat_members
UNION ALL SELECT 'messages', count(*) FROM messages
UNION ALL SELECT 'sessions', count(*) FROM sessions
ORDER BY relation;
SELECT count(*) AS big_chat_rows,
md5(string_agg(id::text || '|' || created_at::text || '|' || encode(text, 'hex'), E'\n' ORDER BY created_at, id)) AS big_chat_md5
FROM messages WHERE chat_id = :'big_chat';
SELECT id, created_at, left(encode(text, 'escape'), 40) AS text FROM messages
WHERE chat_id = :'big_chat' ORDER BY created_at, id LIMIT 3;
SELECT count(*) AS marker_rows FROM messages WHERE position(convert_to('marker after backup', 'UTF8') in text) = 1;