ЛР 2: PostgreSQL, Bearer-сессии и кэш сессий в Valkey (на 4)
Skeleton contracts / contracts (pull_request) Canceled after 0s
Skeleton contracts / contracts (pull_request) Canceled after 0s
- Перенесён минимум lab1; переход 1 → 2: password при регистрации, Basic только на POST /auth/sessions, Bearer вместо X-User-Id, logout. - PostgreSQL — источник истины: users, chats, chat_members, messages, sessions; миграции с PK/FK/UNIQUE/CHECK и индексами, атомарное создание чата, scrypt для паролей, SHA-256 токенов в БД. - Valkey — кэш проверенных сессий с TTL, tombstone при logout, обход кэша и окно недоверия при отказе. - Ограниченные пулы и таймауты PostgreSQL/Valkey, 503 при отказе БД. - compose.yaml с Docker secrets и именованным томом, restart hook, собственные тесты, EXPLAIN на 110 тыс. сообщений, замер пользы кэша, заполненный REPORT.md и evidence/. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -0,0 +1,72 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Польза кэша сессий: нагрузка на PostgreSQL и задержка проверки токена.
|
||||
|
||||
python3 student-tests/cache_bench.py --label valkey [--requests 1000]
|
||||
|
||||
Делает N последовательных GET /api/v1/users/me одним токеном и считает:
|
||||
* прирост xact_commit в pg_stat_database (сколько транзакций выполнила БД);
|
||||
* p50/p95 задержки.
|
||||
Сравнение: запустить при SESSION_CACHE=valkey и при SESSION_CACHE=off (см. REPORT.md).
|
||||
Фоновый шум: healthcheck API (~1 SELECT 1 раз в 5 с).
|
||||
"""
|
||||
import argparse
|
||||
import base64
|
||||
import json
|
||||
import statistics
|
||||
import subprocess
|
||||
import time
|
||||
import urllib.request
|
||||
import uuid
|
||||
from pathlib import Path
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
p = argparse.ArgumentParser()
|
||||
p.add_argument("--base-url", default="http://localhost:8080")
|
||||
p.add_argument("--label", required=True)
|
||||
p.add_argument("--requests", type=int, default=1000)
|
||||
args = p.parse_args()
|
||||
BASE = args.base_url.rstrip("/")
|
||||
|
||||
|
||||
def api(method, path, body=None, headers=None):
|
||||
h = dict(headers or {})
|
||||
data = json.dumps(body).encode() if body is not None else None
|
||||
if data:
|
||||
h["Content-Type"] = "application/json"
|
||||
with urllib.request.urlopen(urllib.request.Request(BASE + path, data=data, headers=h, method=method),
|
||||
timeout=30) as r:
|
||||
return json.loads(r.read() or b"null")
|
||||
|
||||
|
||||
def commits():
|
||||
time.sleep(1.5) # статистика PostgreSQL публикуется с задержкой до ~1 с
|
||||
out = subprocess.run(
|
||||
["docker", "compose", "--env-file", str(ROOT / ".env"), "exec", "-T", "postgres", "psql",
|
||||
"-U", "messenger", "-d", "messenger", "-X", "-A", "-t", "-c",
|
||||
"SELECT xact_commit FROM pg_stat_database WHERE datname = 'messenger'"],
|
||||
cwd=ROOT, check=True, capture_output=True, text=True)
|
||||
return int(out.stdout.strip())
|
||||
|
||||
|
||||
name, pw = "cb_" + uuid.uuid4().hex[:10], "T3st-" + uuid.uuid4().hex
|
||||
api("POST", "/api/v1/users", {"username": name, "display_name": "Cache bench", "password": pw})
|
||||
token = api("POST", "/api/v1/auth/sessions",
|
||||
headers={"Authorization": "Basic " + base64.b64encode((name + ":" + pw).encode()).decode()})["token"]
|
||||
auth = {"Authorization": "Bearer " + token}
|
||||
for _ in range(20): # прогрев соединений
|
||||
api("GET", "/api/v1/users/me", headers=auth)
|
||||
|
||||
before = commits()
|
||||
lat = []
|
||||
for _ in range(args.requests):
|
||||
t0 = time.perf_counter()
|
||||
api("GET", "/api/v1/users/me", headers=auth)
|
||||
lat.append((time.perf_counter() - t0) * 1000)
|
||||
after = commits()
|
||||
lat.sort()
|
||||
print(json.dumps({
|
||||
"label": args.label, "requests": args.requests,
|
||||
"postgres_xact_commit_delta": after - before,
|
||||
"p50_ms": round(statistics.median(lat), 2),
|
||||
"p95_ms": round(lat[int(len(lat) * 0.95) - 1], 2),
|
||||
}, ensure_ascii=False))
|
||||
@@ -0,0 +1,156 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Обоснование индекса истории: EXPLAIN (ANALYZE, BUFFERS) на большом объёме + замер пагинации через API.
|
||||
|
||||
python3 student-tests/history_bench.py [--big 100000] [--small-chats 20] [--small-size 500]
|
||||
|
||||
1. Через API создаёт двух синтетических пользователей, большой чат и N маленьких чатов.
|
||||
2. Через psql (docker compose exec postgres) заливает сообщения: generate_series, одна транзакция.
|
||||
Неравномерно: один чат на --big сообщений, остальные по --small-size.
|
||||
3. Печатает EXPLAIN (ANALYZE, BUFFERS) ровно того SQL, который выполняет приложение:
|
||||
первая страница, «глубокая» страница по keyset-курсору, та же глубина через OFFSET;
|
||||
затем те же запросы БЕЗ индекса messages_chat_order_idx (DROP INDEX внутри BEGIN … ROLLBACK).
|
||||
4. Проходит всю историю большого чата через API (limit=100) и сравнивает задержку первых и
|
||||
последних страниц: при keyset-пагинации она не растёт с номером страницы.
|
||||
|
||||
Каждый запуск добавляет синтетические данные в учебную БД (API курса не удаляет сообщения).
|
||||
"""
|
||||
import argparse
|
||||
import base64
|
||||
import json
|
||||
import statistics
|
||||
import subprocess
|
||||
import time
|
||||
import urllib.parse
|
||||
import urllib.request
|
||||
import uuid
|
||||
from pathlib import Path
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
parser = argparse.ArgumentParser()
|
||||
parser.add_argument("--base-url", default="http://localhost:8080")
|
||||
parser.add_argument("--big", type=int, default=100_000)
|
||||
parser.add_argument("--small-chats", type=int, default=20)
|
||||
parser.add_argument("--small-size", type=int, default=500)
|
||||
args = parser.parse_args()
|
||||
BASE = args.base_url.rstrip("/")
|
||||
|
||||
|
||||
def api(method, path, body=None, headers=None):
|
||||
h = dict(headers or {})
|
||||
data = None
|
||||
if body is not None:
|
||||
data = json.dumps(body).encode()
|
||||
h["Content-Type"] = "application/json"
|
||||
req = urllib.request.Request(BASE + path, data=data, headers=h, method=method)
|
||||
with urllib.request.urlopen(req, timeout=30) as r:
|
||||
raw = r.read()
|
||||
return json.loads(raw) if raw else None
|
||||
|
||||
|
||||
def psql(sql, tuples_only=False):
|
||||
cmd = ["docker", "compose", "--env-file", str(ROOT / ".env"), "exec", "-T", "postgres",
|
||||
"psql", "-U", "messenger", "-d", "messenger", "-X", "-q", "-v", "ON_ERROR_STOP=1"]
|
||||
if tuples_only:
|
||||
cmd += ["-A", "-t"]
|
||||
out = subprocess.run(cmd, input=sql, cwd=ROOT, check=True, capture_output=True, text=True)
|
||||
return out.stdout.strip()
|
||||
|
||||
|
||||
def user(label):
|
||||
name = "bench_%s_%s" % (label, uuid.uuid4().hex[:8])
|
||||
pw = "T3st-" + uuid.uuid4().hex
|
||||
u = api("POST", "/api/v1/users", {"username": name, "display_name": "Bench " + label, "password": pw})
|
||||
cred = base64.b64encode((name + ":" + pw).encode()).decode()
|
||||
s = api("POST", "/api/v1/auth/sessions", headers={"Authorization": "Basic " + cred})
|
||||
return u, {"Authorization": "Bearer " + s["token"]}
|
||||
|
||||
|
||||
def section(title):
|
||||
print("\n" + "=" * 100 + "\n" + title + "\n" + "=" * 100)
|
||||
|
||||
|
||||
# ---------- 1. данные ----------
|
||||
a, ha = user("a")
|
||||
b, _ = user("b")
|
||||
big = api("POST", "/api/v1/chats", {"title": "Большой чат", "member_ids": [a["id"], b["id"]]}, ha)
|
||||
small = [api("POST", "/api/v1/chats", {"title": "Малый %d" % i, "member_ids": [a["id"], b["id"]]}, ha)
|
||||
for i in range(args.small_chats)]
|
||||
|
||||
section("1. Заливка данных")
|
||||
started = time.monotonic()
|
||||
values = ",".join("('%s'::uuid)" % c["id"] for c in small) # UUID получены от нашего API
|
||||
psql("""
|
||||
BEGIN;
|
||||
INSERT INTO messages (id, chat_id, sender_id, text, created_at)
|
||||
SELECT gen_random_uuid(), '{big}'::uuid,
|
||||
CASE WHEN n % 2 = 0 THEN '{a}'::uuid ELSE '{b}'::uuid END,
|
||||
'synthetic message #' || n || ' ' || repeat('x', (n * 7919) % 200),
|
||||
timestamptz '2026-01-01 00:00:00+00' + n * interval '1 millisecond'
|
||||
FROM generate_series(1, {big_n}) AS n;
|
||||
INSERT INTO messages (id, chat_id, sender_id, text, created_at)
|
||||
SELECT gen_random_uuid(), c.id, '{a}'::uuid, 'small chat message #' || n,
|
||||
timestamptz '2026-01-01 00:00:00+00' + n * interval '1 millisecond'
|
||||
FROM (VALUES {values}) AS c(id), generate_series(1, {small_n}) AS n;
|
||||
COMMIT;
|
||||
ANALYZE messages;
|
||||
""".format(big=big["id"], a=a["id"], b=b["id"], big_n=args.big, small_n=args.small_size, values=values))
|
||||
print("залито за %.1f с" % (time.monotonic() - started))
|
||||
print(psql("""SELECT count(*) AS messages_total,
|
||||
count(DISTINCT chat_id) AS chats_with_messages,
|
||||
(SELECT count(*) FROM messages WHERE chat_id = '{big}') AS in_big_chat,
|
||||
pg_size_pretty(pg_relation_size('messages')) AS table_size,
|
||||
pg_size_pretty(pg_relation_size('messages_chat_order_idx')) AS index_size
|
||||
FROM messages""".format(big=big["id"])))
|
||||
|
||||
# ---------- 2. EXPLAIN ----------
|
||||
deep_offset = int(args.big * 0.9)
|
||||
cur_ts, cur_id = psql("""SELECT created_at, id FROM messages WHERE chat_id = '{big}'
|
||||
ORDER BY created_at, id OFFSET {off} LIMIT 1""".format(
|
||||
big=big["id"], off=deep_offset - 1), tuples_only=True).split("|")
|
||||
|
||||
COLS = "SELECT id, chat_id, sender_id, text, created_at FROM messages"
|
||||
Q_FIRST = COLS + " WHERE chat_id = '{c}' ORDER BY created_at, id LIMIT 51".format(c=big["id"])
|
||||
Q_KEYSET = (COLS + " WHERE chat_id = '{c}' AND (created_at, id) > ('{t}', '{i}'::uuid)"
|
||||
" ORDER BY created_at, id LIMIT 51").format(c=big["id"], t=cur_ts, i=cur_id)
|
||||
Q_OFFSET = (COLS + " WHERE chat_id = '{c}' ORDER BY created_at, id OFFSET {o} LIMIT 51").format(
|
||||
c=big["id"], o=deep_offset)
|
||||
EXPLAIN = "EXPLAIN (ANALYZE, BUFFERS, COSTS OFF) "
|
||||
|
||||
for title, q in [
|
||||
("2a. С индексом: первая страница (как в приложении, limit=50 → LIMIT 51)", Q_FIRST),
|
||||
("2b. С индексом: страница после %d-го сообщения, keyset-курсор (как в приложении)" % deep_offset, Q_KEYSET),
|
||||
("2c. Для сравнения: та же глубина через OFFSET %d (так приложение НЕ делает)" % deep_offset, Q_OFFSET)]:
|
||||
section(title)
|
||||
print(q)
|
||||
print(psql(EXPLAIN + q))
|
||||
|
||||
section("2d. БЕЗ индекса messages_chat_order_idx (DROP INDEX внутри BEGIN … ROLLBACK, данные не меняются)")
|
||||
print(psql("BEGIN;\nDROP INDEX messages_chat_order_idx;\n"
|
||||
"\\echo '--- первая страница без индекса'\n" + EXPLAIN + Q_FIRST + ";\n"
|
||||
"\\echo '--- keyset-страница без индекса'\n" + EXPLAIN + Q_KEYSET + ";\nROLLBACK;"))
|
||||
print(psql("SELECT indexname FROM pg_indexes WHERE tablename = 'messages' ORDER BY 1"))
|
||||
|
||||
# ---------- 3. пагинация через API ----------
|
||||
section("3. Полный обход истории большого чата через API (limit=100)")
|
||||
path = "/api/v1/chats/%s/messages?limit=100" % big["id"]
|
||||
latencies, total, cursor = [], 0, None
|
||||
while True:
|
||||
url = path + ("&cursor=" + urllib.parse.quote(cursor, safe="") if cursor else "")
|
||||
t0 = time.perf_counter()
|
||||
page = api("GET", url, headers=ha)
|
||||
latencies.append((time.perf_counter() - t0) * 1000)
|
||||
total += len(page["items"])
|
||||
cursor = page["next_cursor"]
|
||||
if not cursor:
|
||||
break
|
||||
first, last = latencies[1:21], latencies[-20:] # первая страница — прогрев
|
||||
print(json.dumps({
|
||||
"pages": len(latencies), "messages_read": total, "expected": args.big,
|
||||
"first_20_pages_median_ms": round(statistics.median(first), 2),
|
||||
"last_20_pages_median_ms": round(statistics.median(last), 2),
|
||||
"all_pages_p50_ms": round(statistics.median(latencies), 2),
|
||||
"all_pages_p95_ms": round(sorted(latencies)[int(len(latencies) * 0.95) - 1], 2),
|
||||
"all_pages_max_ms": round(max(latencies), 2),
|
||||
}, ensure_ascii=False, indent=1))
|
||||
assert total == args.big, "пагинация потеряла или задублировала сообщения"
|
||||
print("PASS: все %d сообщений прочитаны без потерь и повторов" % total)
|
||||
@@ -0,0 +1,364 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Собственные проверки lab2 (только stdlib): аутентификация, границы, транзакции, сохранность.
|
||||
|
||||
python3 student-tests/test_lab2.py # граничные проверки, гонка, атомарность
|
||||
python3 student-tests/test_lab2.py --expiry-url http://localhost:8081 # + истечение (SESSION_TTL_SECONDS=2)
|
||||
python3 student-tests/test_lab2.py --db-outage # + остановка PostgreSQL -> 503, восстановление
|
||||
python3 student-tests/test_lab2.py --persistence # + перезапуск API и БД через scripts/restart.sh
|
||||
|
||||
Токены и пароли не печатаются. Флаги --db-outage/--persistence управляют docker compose.
|
||||
"""
|
||||
import argparse
|
||||
import base64
|
||||
import json
|
||||
import subprocess
|
||||
import sys
|
||||
import threading
|
||||
import time
|
||||
import urllib.error
|
||||
import urllib.request
|
||||
import uuid
|
||||
from pathlib import Path
|
||||
|
||||
parser = argparse.ArgumentParser()
|
||||
parser.add_argument("--base-url", default="http://localhost:8080")
|
||||
parser.add_argument("--persistence", action="store_true")
|
||||
parser.add_argument("--expiry-url", default=None, help="экземпляр API с SESSION_TTL_SECONDS=2")
|
||||
parser.add_argument("--db-outage", action="store_true")
|
||||
parser.add_argument("--cache", action="store_true",
|
||||
help="проверки Valkey: отказ, FLUSHALL, зависание при logout (docker compose)")
|
||||
args = parser.parse_args()
|
||||
BASE = args.base_url.rstrip("/")
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
fails = 0
|
||||
|
||||
|
||||
def call(method, path, body=None, token=None, headers=None, raw=None, base=None):
|
||||
h = dict(headers or {})
|
||||
if token:
|
||||
h["Authorization"] = "Bearer " + token
|
||||
data = raw if raw is not None else (json.dumps(body, ensure_ascii=False).encode() if body is not None else None)
|
||||
if data is not None:
|
||||
h.setdefault("Content-Type", "application/json")
|
||||
req = urllib.request.Request((base or BASE) + path, data=data, headers=h, method=method)
|
||||
try:
|
||||
resp = urllib.request.urlopen(req, timeout=30)
|
||||
except urllib.error.HTTPError as err:
|
||||
resp = err
|
||||
with resp:
|
||||
text = resp.read()
|
||||
assert resp.headers.get("X-Request-Id"), "нет X-Request-Id"
|
||||
return resp.code, (json.loads(text) if text else None), resp.headers
|
||||
|
||||
|
||||
def expect(name, got, want):
|
||||
global fails
|
||||
ok = got == want
|
||||
fails += not ok
|
||||
short = lambda v: (str(v)[:40] + "…") if len(str(v)) > 40 else str(v)
|
||||
print("%-4s %-46s -> %s (ожидалось %s)" % ("OK" if ok else "FAIL", name, short(got), short(want)))
|
||||
|
||||
|
||||
def basic(username, password):
|
||||
return {"Authorization": "Basic " + base64.b64encode((username + ":" + password).encode()).decode()}
|
||||
|
||||
|
||||
def register(prefix, password):
|
||||
username = prefix + uuid.uuid4().hex[:8]
|
||||
code, user, _ = call("POST", "/api/v1/users", {"username": username, "display_name": "Тест", "password": password})
|
||||
assert code == 201, code
|
||||
return user
|
||||
|
||||
|
||||
def login(username, password):
|
||||
code, session, _ = call("POST", "/api/v1/auth/sessions", headers=basic(username, password))
|
||||
assert code == 201, code
|
||||
return session["token"]
|
||||
|
||||
|
||||
PW_A, PW_B = "Пароль:с:двоеточием-Ω1", "T3st-" + uuid.uuid4().hex
|
||||
a, b, e = register("a_", PW_A), register("b_", PW_B), register("e_", PW_B)
|
||||
ta, tb, te = login(a["username"], PW_A), login(b["username"], PW_B), login(e["username"], PW_B)
|
||||
|
||||
# --- регистрация ---
|
||||
users = "/api/v1/users"
|
||||
expect("регистрация без password", call("POST", users, {"username": "zz_" + uuid.uuid4().hex[:6], "display_name": "x"})[0], 400)
|
||||
expect("password 11 символов", call("POST", users, {"username": "zz_" + uuid.uuid4().hex[:6], "display_name": "x", "password": "a" * 11})[0], 400)
|
||||
expect("password 129 символов", call("POST", users, {"username": "zz_" + uuid.uuid4().hex[:6], "display_name": "x", "password": "a" * 129})[0], 400)
|
||||
expect("password не строка", call("POST", users, {"username": "zz_" + uuid.uuid4().hex[:6], "display_name": "x", "password": 123456789012})[0], 400)
|
||||
expect("дубликат username", call("POST", users, {"username": a["username"], "display_name": "x", "password": PW_B})[0], 409)
|
||||
expect("User не содержит пароль/хеш", sorted(a), ["created_at", "display_name", "id", "username"])
|
||||
expect("malformed JSON", call("POST", users, raw=b"{bad")[0], 400)
|
||||
|
||||
# --- вход ---
|
||||
sess = "/api/v1/auth/sessions"
|
||||
code, _, hdr = call("POST", sess, headers=basic(a["username"], "wrong-password-123"))
|
||||
expect("неверный пароль", code, 401)
|
||||
expect(" challenge Basic", hdr.get("WWW-Authenticate", "").startswith("Basic"), True)
|
||||
expect("неизвестный пользователь", call("POST", sess, headers=basic("no_such_user_x", PW_B))[0], 401)
|
||||
expect("вход без Authorization", call("POST", sess)[0], 401)
|
||||
expect("вход с Bearer вместо Basic", call("POST", sess, token=ta)[0], 401)
|
||||
expect("мусор вместо base64", call("POST", sess, headers={"Authorization": "Basic !!!"})[0], 401)
|
||||
expect("пароль с двоеточием и Unicode", call("GET", "/api/v1/users/me", token=ta)[1]["id"], a["id"])
|
||||
t1, t2 = login(b["username"], PW_B), login(b["username"], PW_B)
|
||||
expect("два входа дают разные токены", t1 != t2 and len(t1) >= 43, True)
|
||||
|
||||
# --- Bearer ---
|
||||
me = "/api/v1/users/me"
|
||||
code, _, hdr = call("GET", me)
|
||||
expect("без токена", code, 401)
|
||||
expect(" challenge Bearer", hdr.get("WWW-Authenticate", "").startswith("Bearer"), True)
|
||||
expect("случайный токен", call("GET", me, token="x" * 43)[0], 401)
|
||||
expect("Basic на бизнес-endpoint", call("GET", me, headers=basic(a["username"], PW_A))[0], 401)
|
||||
expect("только X-User-Id", call("GET", me, headers={"X-User-Id": a["id"]})[0], 401)
|
||||
expect("X-User-Id не меняет владельца", call("GET", me, token=ta, headers={"X-User-Id": e["id"]})[1]["id"], a["id"])
|
||||
|
||||
# --- logout ---
|
||||
expect("logout", call("DELETE", sess + "/current", token=t1)[0], 204)
|
||||
expect("отозванный токен", call("GET", me, token=t1)[0], 401)
|
||||
expect("повторный logout", call("DELETE", sess + "/current", token=t1)[0], 401)
|
||||
expect("другая сессия того же пользователя жива", call("GET", me, token=t2)[0], 200)
|
||||
|
||||
# --- чаты и сообщения ---
|
||||
chats = "/api/v1/chats"
|
||||
expect("чат: создатель не участник", call("POST", chats, {"title": "t", "member_ids": [b["id"]]}, ta)[0], 400)
|
||||
expect("чат: неизвестный участник", call("POST", chats, {"title": "t", "member_ids": [a["id"], str(uuid.uuid4())]}, ta)[0], 400)
|
||||
expect("чат: дубликат участника", call("POST", chats, {"title": "t", "member_ids": [a["id"], a["id"]]}, ta)[0], 400)
|
||||
chat = call("POST", chats, {"title": "Проверка", "member_ids": [a["id"], b["id"]]}, ta)[1]
|
||||
chat2 = call("POST", chats, {"title": "t2", "member_ids": [a["id"]]}, ta)[1]
|
||||
expect("порядок member_ids сохранён", chat["member_ids"], [a["id"], b["id"]])
|
||||
msgs = "/api/v1/chats/%s/messages" % chat["id"]
|
||||
expect("чужой чат (Ева)", call("GET", chats + "/" + chat["id"], token=te)[0], 404)
|
||||
expect("запись в чужой чат (Ева)", call("POST", msgs, {"text": "x"}, te)[0], 404)
|
||||
expect("пустое сообщение", call("POST", msgs, {"text": " "}, ta)[0], 400)
|
||||
expect("sender_id в теле", call("POST", msgs, {"text": "x", "sender_id": b["id"]}, ta)[0], 400)
|
||||
expect("4001 символ", call("POST", msgs, {"text": "я" * 4001}, ta)[0], 400)
|
||||
|
||||
errors = []
|
||||
|
||||
|
||||
def send(i):
|
||||
try:
|
||||
code, _, _ = call("POST", msgs, {"text": "m%d 👋" % i}, ta if i % 2 else tb)
|
||||
if code != 201:
|
||||
errors.append(code)
|
||||
except Exception as exc:
|
||||
errors.append(type(exc).__name__)
|
||||
|
||||
|
||||
threads = [threading.Thread(target=send, args=(i,)) for i in range(100)]
|
||||
[t.start() for t in threads]
|
||||
[t.join() for t in threads]
|
||||
|
||||
|
||||
def read_all(token, limit=7):
|
||||
seen, cursor = [], None
|
||||
while True:
|
||||
_, page, _ = call("GET", msgs + "?limit=%d" % limit + ("&cursor=" + cursor if cursor else ""), token=token)
|
||||
seen += page["items"]
|
||||
cursor = page["next_cursor"]
|
||||
if not cursor:
|
||||
return seen
|
||||
|
||||
|
||||
history = read_all(tb)
|
||||
expect("100 параллельных POST: ошибок", len(errors), 0)
|
||||
expect("100 параллельных POST: уникальных", len({m["id"] for m in history}), 100)
|
||||
expect("история отсортирована (created_at, id)",
|
||||
history == sorted(history, key=lambda m: (m["created_at"], uuid.UUID(m["id"]).int)), True)
|
||||
first = call("GET", msgs + "?limit=1", token=ta)[1]
|
||||
expect("cursor от другого чата", call("GET", "/api/v1/chats/%s/messages?cursor=%s" % (chat2["id"], first["next_cursor"]), token=ta)[0], 400)
|
||||
expect("мусорный cursor", call("GET", msgs + "?cursor=abc", token=ta)[0], 400)
|
||||
expect("limit=0", call("GET", msgs + "?limit=0", token=ta)[0], 400)
|
||||
expect("неверный UUID в пути", call("GET", chats + "/xyz", token=ta)[0], 400)
|
||||
|
||||
# --- гонка регистрации одного username ---
|
||||
race_name = "race_" + uuid.uuid4().hex[:10]
|
||||
race_codes = []
|
||||
|
||||
|
||||
def register_same():
|
||||
try:
|
||||
race_codes.append(call("POST", "/api/v1/users",
|
||||
{"username": race_name, "display_name": "Гонка", "password": PW_B})[0])
|
||||
except Exception as exc:
|
||||
race_codes.append(type(exc).__name__)
|
||||
|
||||
|
||||
threads = [threading.Thread(target=register_same) for _ in range(20)]
|
||||
[t.start() for t in threads]
|
||||
[t.join() for t in threads]
|
||||
expect("гонка 20 регистраций: ровно один 201", sorted(race_codes).count(201), 1)
|
||||
expect("гонка 20 регистраций: остальные 409", sorted(race_codes).count(409), 19)
|
||||
|
||||
# --- атомарность создания чата: ошибка не оставляет «полу-чата» ---
|
||||
def chat_ids(token):
|
||||
_, page, _ = call("GET", chats + "?limit=100", token=token)
|
||||
return [c["id"] for c in page["items"]]
|
||||
|
||||
|
||||
fresh_pw = "T3st-" + uuid.uuid4().hex
|
||||
fresh = register("f_", fresh_pw)
|
||||
tf = login(fresh["username"], fresh_pw)
|
||||
before = chat_ids(tf)
|
||||
before_b = chat_ids(tb)
|
||||
code = call("POST", chats, {"title": "откат", "member_ids": [fresh["id"], b["id"], str(uuid.uuid4())]}, tf)[0]
|
||||
expect("чат с неизвестным 3-м участником", code, 400)
|
||||
expect("после ошибки чат не появился у создателя", chat_ids(tf), before)
|
||||
expect("после ошибки чат не появился у участника b", chat_ids(tb), before_b)
|
||||
code, ok_chat, _ = call("POST", chats, {"title": "после отката", "member_ids": [fresh["id"]]}, tf)
|
||||
expect("следующее создание чата работает", (code, chat_ids(tf)), (201, before + [ok_chat["id"]]))
|
||||
|
||||
# --- истечение сессии (отдельный экземпляр API с SESSION_TTL_SECONDS=2) ---
|
||||
if args.expiry_url:
|
||||
eb = args.expiry_url.rstrip("/")
|
||||
code, s, _ = call("POST", sess, headers=basic(a["username"], PW_A), base=eb)
|
||||
expect("TTL=2: вход", code, 201)
|
||||
expect("TTL=2: сразу после входа токен работает", call("GET", me, token=s["token"], base=eb)[0], 200)
|
||||
time.sleep(3)
|
||||
code, _, hdr = call("GET", me, token=s["token"], base=eb)
|
||||
expect("TTL=2: через 3 с токен истёк", code, 401)
|
||||
expect(" challenge Bearer", hdr.get("WWW-Authenticate", "").startswith("Bearer"), True)
|
||||
expect("TTL=2: истёкший токен не работает и на основном API", call("GET", me, token=s["token"])[0], 401)
|
||||
|
||||
# --- недоступность PostgreSQL ---
|
||||
if args.db_outage:
|
||||
print("--- остановка PostgreSQL: docker compose stop postgres")
|
||||
compose = ["docker", "compose", "--env-file", str(ROOT / ".env")]
|
||||
subprocess.run(compose + ["stop", "postgres"], cwd=ROOT, check=True,
|
||||
stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
|
||||
try:
|
||||
code, body, _ = call("GET", "/health/ready")
|
||||
expect("БД нет: /health/ready", (code, body["error"]["code"]), (503, "unavailable"))
|
||||
expect("БД нет: /health/live", call("GET", "/health/live")[0], 200)
|
||||
started = time.monotonic()
|
||||
code, body, _ = call("GET", chats, token=ta)
|
||||
expect("БД нет: список чатов с токеном -> 503, не 200", (code, body["error"]["code"]), (503, "unavailable"))
|
||||
expect("БД нет: ответ ограничен по времени (<10 с)", time.monotonic() - started < 10, True)
|
||||
# /users/me может быть отдан из кэша сессий (копия действующей сессии, отзыв без БД невозможен)
|
||||
expect("БД нет: /users/me -> 200 из кэша или 503", call("GET", me, token=ta)[0] in (200, 503), True)
|
||||
expect("БД нет: неизвестный токен не проходит", call("GET", me, token="y" * 43)[0] in (401, 503), True)
|
||||
expect("БД нет: анонимный запрос не проходит", call("GET", me)[0] in (401, 503), True)
|
||||
expect("БД нет: вход -> 503", call("POST", sess, headers=basic(a["username"], PW_A))[0], 503)
|
||||
finally:
|
||||
subprocess.run(compose + ["start", "postgres"], cwd=ROOT, check=True,
|
||||
stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
|
||||
deadline = time.monotonic() + 60
|
||||
while call("GET", "/health/ready")[0] != 200:
|
||||
assert time.monotonic() < deadline, "БД не восстановилась"
|
||||
time.sleep(1)
|
||||
expect("БД вернулась: прежний токен работает", call("GET", me, token=ta)[1], a)
|
||||
|
||||
|
||||
# --- Valkey: роль кэша, отказ, flush, зависание при logout ---
|
||||
if args.cache:
|
||||
compose = ["docker", "compose", "--env-file", str(ROOT / ".env")]
|
||||
|
||||
def dc(*cmd):
|
||||
subprocess.run(compose + list(cmd), cwd=ROOT, check=True,
|
||||
stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
|
||||
|
||||
def vcli(*cmd):
|
||||
"""valkey-cli внутри контейнера; пароль читается там же из секрета и не печатается."""
|
||||
out = subprocess.run(compose + ["exec", "-T", "valkey", "sh", "-c",
|
||||
'valkey-cli --no-auth-warning -a "$(sed -n "s/^requirepass //p" '
|
||||
'/run/secrets/valkey.conf)" "$@"', "_"] + list(cmd),
|
||||
cwd=ROOT, check=True, capture_output=True, text=True)
|
||||
return out.stdout.strip()
|
||||
|
||||
def stats():
|
||||
info = dict(l.split(":", 1) for l in vcli("INFO", "stats").splitlines() if ":" in l)
|
||||
return int(info["keyspace_hits"]), int(info["keyspace_misses"])
|
||||
|
||||
import hashlib
|
||||
|
||||
def cache_value(token):
|
||||
return vcli("GET", "sess:" + hashlib.sha256(token.encode()).hexdigest())
|
||||
|
||||
pw = "T3st-" + uuid.uuid4().hex
|
||||
cu = register("c_", pw)
|
||||
tc = login(cu["username"], pw)
|
||||
expect("кэш: после входа в Valkey лежит копия сессии", cu["id"] in cache_value(tc), True)
|
||||
expect("кэш: в Valkey нет самого токена/пароля", tc not in vcli("--scan", "--pattern", "*") and True, True)
|
||||
h0, m0 = stats()
|
||||
for _ in range(50):
|
||||
call("GET", me, token=tc)
|
||||
h1, m1 = stats()
|
||||
expect("кэш: 50 запросов -> 50 попаданий в Valkey", (h1 - h0, m1 - m0), (50, 0))
|
||||
|
||||
# logout мгновенно виден через кэш
|
||||
t2 = login(cu["username"], pw)
|
||||
call("GET", me, token=t2)
|
||||
expect("кэш: logout", call("DELETE", sess + "/current", token=t2)[0], 204)
|
||||
expect("кэш: в Valkey tombstone вместо копии", cache_value(t2), "revoked")
|
||||
expect("кэш: отозванный токен сразу 401", call("GET", me, token=t2)[0], 401)
|
||||
|
||||
# FLUSHALL: кэш пуст, сессии читаются из PostgreSQL
|
||||
vcli("FLUSHALL")
|
||||
expect("FLUSHALL: действующий токен работает (из БД)", call("GET", me, token=tc)[1], cu)
|
||||
expect("FLUSHALL: отозванный токен по-прежнему 401", call("GET", me, token=t2)[0], 401)
|
||||
expect("FLUSHALL: кэш снова заполнен после промаха", cu["id"] in cache_value(tc), True)
|
||||
|
||||
# Valkey остановлен: API работает через PostgreSQL
|
||||
print("--- остановка Valkey: docker compose stop valkey")
|
||||
dc("stop", "valkey")
|
||||
try:
|
||||
expect("Valkey нет: /health/ready 200 (не критичен)", call("GET", "/health/ready")[0], 200)
|
||||
started = time.monotonic()
|
||||
expect("Valkey нет: токен работает через БД", call("GET", me, token=tc)[1], cu)
|
||||
expect("Valkey нет: ответ быстрый (<2 с)", time.monotonic() - started < 2, True)
|
||||
expect("Valkey нет: список чатов", call("GET", chats, token=tc)[0], 200)
|
||||
expect("Valkey нет: без токена 401", call("GET", me)[0], 401)
|
||||
expect("Valkey нет: чужой токен 401", call("GET", me, token="z" * 43)[0], 401)
|
||||
expect("Valkey нет: отозванный токен 401", call("GET", me, token=t2)[0], 401)
|
||||
t3 = login(cu["username"], pw)
|
||||
expect("Valkey нет: вход 201", bool(t3), True)
|
||||
expect("Valkey нет: logout 204", call("DELETE", sess + "/current", token=t3)[0], 204)
|
||||
expect("Valkey нет: после logout 401", call("GET", me, token=t3)[0], 401)
|
||||
finally:
|
||||
dc("start", "valkey")
|
||||
deadline = time.monotonic() + 30
|
||||
while "PONG" not in vcli("PING"):
|
||||
assert time.monotonic() < deadline, "Valkey не поднялся"
|
||||
time.sleep(0.5)
|
||||
time.sleep(6) # дольше CACHE_RETRY_SECONDS: приложение снова опрашивает кэш
|
||||
expect("Valkey вернулся: токен работает", call("GET", me, token=tc)[1], cu)
|
||||
expect("Valkey вернулся: кэш снова заполняется", cu["id"] in cache_value(tc), True)
|
||||
expect("Valkey вернулся: токен, отозванный при отказе, 401", call("GET", me, token=t3)[0], 401)
|
||||
|
||||
# Самый опасный случай: Valkey «завис» (pause) во время logout -> tombstone не записан,
|
||||
# в Valkey осталась положительная копия сессии. Она не должна «воскресить» токен.
|
||||
t4 = login(cu["username"], pw)
|
||||
call("GET", me, token=t4)
|
||||
print("--- зависание Valkey во время logout: docker compose pause valkey")
|
||||
dc("pause", "valkey")
|
||||
try:
|
||||
expect("Valkey завис: logout всё равно 204 (отзыв в БД)", call("DELETE", sess + "/current", token=t4)[0], 204)
|
||||
finally:
|
||||
dc("unpause", "valkey")
|
||||
expect("Valkey ожил: в нём осталась устаревшая копия", cu["id"] in cache_value(t4), True)
|
||||
time.sleep(6) # breaker закрыт, кэш снова опрашивается
|
||||
expect("Valkey ожил: устаревшая копия не принята, 401", call("GET", me, token=t4)[0], 401)
|
||||
expect("Valkey ожил: действующий токен работает", call("GET", me, token=tc)[1], cu)
|
||||
|
||||
|
||||
if args.persistence:
|
||||
print("--- перезапуск API и PostgreSQL: scripts/restart.sh")
|
||||
subprocess.run([str(ROOT / "scripts" / "restart.sh")], check=True, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
|
||||
deadline = time.monotonic() + 90
|
||||
while True:
|
||||
try:
|
||||
if call("GET", "/health/ready")[0] == 200:
|
||||
break
|
||||
except Exception:
|
||||
pass
|
||||
assert time.monotonic() < deadline, "сервер не поднялся"
|
||||
time.sleep(1)
|
||||
expect("после рестарта: прежний токен работает", call("GET", me, token=ta)[1], a)
|
||||
expect("после рестарта: чат на месте", call("GET", chats + "/" + chat["id"], token=tb)[1], chat)
|
||||
expect("после рестарта: история та же", read_all(tb), history)
|
||||
expect("после рестарта: отозванный токен всё ещё отозван", call("GET", me, token=t1)[0], 401)
|
||||
expect("после рестарта: вход по паролю работает", call("POST", sess, headers=basic(a["username"], PW_A))[0], 201)
|
||||
|
||||
print("ИТОГО:", "ВСЕ ПРОВЕРКИ ПРОШЛИ" if not fails else "%d ПРОВАЛОВ" % fails)
|
||||
sys.exit(1 if fails else 0)
|
||||
Reference in New Issue
Block a user